diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/back-compatible.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/back-compatible.tsp new file mode 100644 index 00000000000..2a912c128d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/back-compatible.tsp @@ -0,0 +1,36 @@ +import "@azure-tools/typespec-client-generator-core"; +import "./privateEndpointConnection.tsp"; +import "./experimentExecution.tsp"; +import "./privateAccess.tsp"; + +using Azure.ClientGenerator.Core; +using Microsoft.Chaos; + +// PrivateEndpointConnections interface operations with PrivateAccesses_ prefix +@@clientLocation(PrivateEndpointConnections.getAPrivateEndpointConnection, + PrivateAccesses, + "!csharp" +); +@@clientLocation(PrivateEndpointConnections.deleteAPrivateEndpointConnection, + PrivateAccesses, + "!csharp" +); +@@clientLocation(PrivateEndpointConnections.listPrivateEndpointConnections, + PrivateAccesses, + "!csharp" +); + +// ExperimentExecutions interface operations with Experiments_ prefix +@@clientLocation(ExperimentExecutions.getExecution, Experiments, "!csharp"); +@@clientLocation(ExperimentExecutions.listAllExecutions, + Experiments, + "!csharp" +); +@@clientLocation(ExperimentExecutions.getExecutionDetails, + Experiments, + "!csharp" +); + +@@clientName(Operations.list, "ListAll", "autorest"); +@@clientName(ExperimentExecutions.getExecutionDetails, "ExecutionDetails"); +@@clientName(PrivateAccesses.privateLinkResources, "GetPrivateLinkResources"); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/capability.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/capability.models.tsp new file mode 100644 index 00000000000..1ddc9c15fa9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/capability.models.tsp @@ -0,0 +1,80 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./common.models.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.Chaos; + +/** + * Model that represents a Capability resource. + */ +@parentResource(Target) +model Capability is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = Capability, + KeyName = "capabilityName", + SegmentName = "capabilities", + NamePattern = "^[a-zA-Z0-9\\-\\.]+-\\d\\.\\d$" + >; +} + +alias CapabilityParentResourceParameters = BaseParameters & + ParentResourceParameters; + +/** + * Model that represents the Capability properties model. + */ +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "Unused property, avoids breaking changes in SDK." +model CapabilityProperties { + /** + * String of the Publisher that this Capability extends. + */ + @visibility(Lifecycle.Read) + publisher?: string; + + /** + * String of the Target Type that this Capability extends. + */ + @visibility(Lifecycle.Read) + targetType?: string; + + /** + * Localized string of the description. + */ + @visibility(Lifecycle.Read) + description?: string; + + /** + * URL to retrieve JSON schema of the Capability parameters. + */ + @visibility(Lifecycle.Read) + @maxLength(2048) + parametersSchema?: string; + + /** + * String of the URN for this Capability Type. + */ + @visibility(Lifecycle.Read) + @maxLength(2048) + urn?: string; + + /** + * Resource provisioning state. Not currently in use because resource is created synchronously. + */ + @removed(Microsoft.Chaos.Versions.v2025_01_01) + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Model that represents a list of Capability resources and a link for pagination. + */ +model CapabilityListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/capability.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/capability.tsp new file mode 100644 index 00000000000..0de251d4d6b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/capability.tsp @@ -0,0 +1,61 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./capability.models.tsp"; +import "./target.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +@armResourceOperations +interface Capabilities { + /** + * Get a Capability resource that extends a Target resource. + */ + get is ArmResourceRead; + + /** + * Create or update a Capability resource that extends a Target resource. + */ + createOrUpdate is ArmResourceCreateOrReplaceSync< + Capability, + CapabilityParentResourceParameters + >; + + /** + * Delete a Capability that extends a Target resource. + */ + delete is ArmResourceDeleteSync< + Capability, + CapabilityParentResourceParameters + >; + + /** + * Get a list of Capability resources that extend a Target resource. + */ + list is ArmResourceListByParent< + Capability, + { + ...CapabilityParentResourceParameters; + + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = CapabilityListResult + >; +} + +@@doc(Capability.name, "String that represents a Capability resource name."); +@@doc(Capability.properties, "The properties of a capability resource."); +@@doc(Capabilities.createOrUpdate::parameters.resource, + "Capability resource to be created or updated." +); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/capabilityType.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/capabilityType.models.tsp new file mode 100644 index 00000000000..b88eb972d24 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/capabilityType.models.tsp @@ -0,0 +1,118 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.Chaos; + +/** + * Model that represents a Capability Type resource. + */ +@parentResource(TargetType) +model CapabilityType + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = CapabilityType, + KeyName = "capabilityTypeName", + SegmentName = "capabilityTypes", + NamePattern = "^[a-zA-Z0-9\\-\\.]+-\\d\\.\\d$" + >; +} + +/** + * Model that represents the Capability Type properties model. + */ +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "Read-only metadata resource." +model CapabilityTypeProperties { + /** + * String of the Publisher that this Capability Type extends. + */ + @visibility(Lifecycle.Read) + publisher?: string; + + /** + * String of the Target Type that this Capability Type extends. + */ + @visibility(Lifecycle.Read) + targetType?: string; + + /** + * Localized string of the display name. + */ + @visibility(Lifecycle.Read) + displayName?: string; + + /** + * Localized string of the description. + */ + @visibility(Lifecycle.Read) + description?: string; + + /** + * URL to retrieve JSON schema of the Capability Type parameters. + */ + @visibility(Lifecycle.Read) + @maxLength(2048) + parametersSchema?: string; + + /** + * String of the URN for this Capability Type. + */ + @visibility(Lifecycle.Read) + @maxLength(2048) + urn?: string; + + /** + * String of the kind of this Capability Type. + */ + @visibility(Lifecycle.Read) + kind?: string; + + /** + * Control plane actions necessary to execute capability type. + */ + @visibility(Lifecycle.Read) + azureRbacActions?: string[]; + + /** + * Data plane actions necessary to execute capability type. + */ + @visibility(Lifecycle.Read) + azureRbacDataActions?: string[]; + + /** + * Required Azure Role Definition Ids to execute capability type. + */ + @visibility(Lifecycle.Read) + @added(Microsoft.Chaos.Versions.v2025_01_01) + requiredAzureRoleDefinitionIds?: string[]; + + /** + * Runtime properties of this Capability Type. + */ + @visibility(Lifecycle.Read) + runtimeProperties?: CapabilityTypePropertiesRuntimeProperties; +} + +/** + * Runtime properties of this Capability Type. + */ +model CapabilityTypePropertiesRuntimeProperties { + /** + * String of the kind of the resource's action type (continuous or discrete). + */ + @visibility(Lifecycle.Read) + kind?: string; +} + +/** + * Model that represents a list of Capability Type resources and a link for pagination. + */ +model CapabilityTypeListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/capabilityType.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/capabilityType.tsp new file mode 100644 index 00000000000..1db39b94ba7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/capabilityType.tsp @@ -0,0 +1,42 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./capabilityType.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +@armResourceOperations +interface CapabilityTypes { + /** + * Get a Capability Type resource for given Target Type and location. + */ + get is ArmResourceRead; + + /** + * Get a list of Capability Type resources for given Target Type and location. + */ + list is ArmResourceListByParent< + CapabilityType, + Parameters = { + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = CapabilityTypeListResult + >; +} + +@@doc(CapabilityType.name, + "String that represents a Capability Type resource name." +); +@@doc(CapabilityType.properties, + "The properties of the capability type resource." +); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/client.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/client.tsp new file mode 100644 index 00000000000..2c304199d01 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/client.tsp @@ -0,0 +1,66 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; +using Microsoft.Chaos; + +// csharp +@@clientName(ExperimentExecution, "ChaosExperimentExecution", "csharp"); +@@clientName(Experiment, "ChaosExperiment", "csharp"); +@@clientName(ExperimentExecution, "ChaosExperimentExecution", "csharp"); +@@clientName(Target, "ChaosTarget", "csharp"); +@@clientName(TargetType, "ChaosTargetMetadata", "csharp"); +@@clientName(Capability, "ChaosCapability", "csharp"); +@@clientName(CapabilityType, "ChaosCapabilityMetadata", "csharp"); +@@clientName(TargetReference, "ChaosTargetReference", "csharp"); +@@clientName(TargetReferenceType, "ChaosTargetReferenceType", "csharp"); +@@clientName(ProvisioningState, "ChaosProvisioningState", "csharp"); +@@clientName(KeyValuePair, "ChaosKeyValuePair", "csharp"); +@@clientName(StepStatus, "ChaosExperimentRunStepStatus", "csharp"); +@@clientName(BranchStatus, "ChaosExperimentRunBranchStatus", "csharp"); +@@clientName(ActionStatus, "ChaosExperimentRunActionStatus", "csharp"); +@@clientName(ContinuousAction, "ChaosContinuousAction", "csharp"); +@@clientName(DiscreteAction, "ChaosDiscreteAction", "csharp"); +@@clientName(DelayAction, "ChaosDelayAction", "csharp"); +@@clientName(CapabilityTypePropertiesRuntimeProperties, + "ChaosCapabilityMetadataRuntimeProperties", + "csharp" +); +@@clientName(TargetReference.type, "ReferenceType", "csharp"); +@@clientName(ExperimentExecutions.getExecutionDetails, + "ExecutionDetails", + "csharp" +); +@@scope(Microsoft.Chaos.OperationStatuses.get, "!csharp"); + +// typescript +@@clientName(Microsoft.Chaos, "ChaosManagementClient", "javascript"); + +// python +@@clientName(Microsoft.Chaos, "ChaosManagementClient", "python"); + +// java +@@clientName(Microsoft.Chaos, "ChaosManagementClient", "java"); +@@clientName(Azure.ResourceManager.Foundations.ManagedServiceIdentity, + "ResourceIdentity", + "java" +); +@@clientName(Azure.ResourceManager.CommonTypes.OperationStatusResult, + "OperationStatus", + "java" +); + +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(Experiment.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(ExperimentExecution.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(TargetType.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(Capability.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(CapabilityType.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(ExperimentExecutionDetails.properties); + +@@clientName(Microsoft.Chaos.Operations.list, "listAll", "javascript,python"); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/common.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/common.models.tsp new file mode 100644 index 00000000000..457b7cca365 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/common.models.tsp @@ -0,0 +1,98 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +interface Operations extends Azure.ResourceManager.Operations {} +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to avoid breaking SDK change" +alias ParentResourceParameters = { + /** + * The parent resource provider namespace. + */ + @path + @segment("providers") + @maxLength(63) + @pattern("^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$") + parentProviderNamespace: string; + + /** + * The parent resource type. + */ + @path + @maxLength(63) + @pattern("^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$") + parentResourceType: string; + + /** + * The parent resource name. + */ + @path + @maxLength(63) + @pattern("^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$") + parentResourceName: string; +}; + +/** + * Current provisioning state for a given Azure Chaos resource. + */ +@Azure.Core.lroStatus +union ProvisioningState { + string, + ResourceProvisioningState, + + /** + * Initial creation in progress. + */ + Creating: "Creating", + + /** + * Update in progress. + */ + Updating: "Updating", + + /** + * Deletion in progress. + */ + Deleting: "Deleting", +} + +/** + * The status of operation. + */ +#suppress "@azure-tools/typespec-azure-core/composition-over-inheritance" "For backward compatibility" +model OperationStatus extends ErrorResponse { + /** + * The operation Id. + */ + id?: string; + + /** + * The operation name. + */ + name?: string; + + /** + * The start time of the operation. + */ + @visibility(Lifecycle.Read) + startTime?: utcDateTime; + + /** + * The end time of the operation. + */ + @visibility(Lifecycle.Read) + endTime?: utcDateTime; + + /** + * The status of the operation. + */ + status?: string; +} diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/experiment.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/experiment.models.tsp new file mode 100644 index 00000000000..b7bfb4a20ca --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/experiment.models.tsp @@ -0,0 +1,390 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./common.models.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.Chaos; +/** + * Model that represents a Experiment resource. + */ +#suppress "@azure-tools/typespec-azure-core/no-private-usage" "Required implementation to avoid breaking .NET SDK changes" +#suppress "@azure-tools/typespec-azure-core/composition-over-inheritance" "Required implementation to avoid breaking .NET SDK changes" +@Azure.ResourceManager.Private.armResourceInternal(ExperimentProperties) +@Http.Private.includeInapplicableMetadataInPayload(false) +model Experiment extends Azure.ResourceManager.Foundations.TrackedResource { + ...ResourceNameParameter< + Resource = Experiment, + KeyName = "experimentName", + SegmentName = "experiments", + NamePattern = "^[^<>%&:?#/\\\\]+$" + >; + ...Azure.ResourceManager.ManagedServiceIdentityProperty; + + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "Required implementation to avoid breaking .NET SDK changes" + @doc("The resource-specific properties for this resource.") + @Azure.ResourceManager.Private.conditionalClientFlatten + @Azure.ResourceManager.Private.armResourcePropertiesOptionality(false) + properties?: ExperimentProperties; +} + +/** + * Enum of the selector type. + */ +union SelectorType { + string, + + /** + * List selector type. + */ + List: "List", + + /** + * Query selector type. + */ + Query: "Query", +} + +/** + * Enum that discriminates between filter types. Currently only `Simple` type is supported. + */ +union FilterType { + string, + + /** + * Simple filter type. + */ + Simple: "Simple", +} + +/** + * Enum of the Target reference type. + */ +union TargetReferenceType { + string, + + /** + * Chaos target reference type. + */ + ChaosTarget: "ChaosTarget", +} + +/** + * Enum union of Chaos experiment action types. + */ +union ExperimentActionType { + string, + delay: "delay", + discrete: "discrete", + continuous: "continuous", +} + +/** + * Model that represents a list of Experiment resources and a link for pagination. + */ +model ExperimentListResult is Azure.Core.Page; + +/** + * Model that represents the Experiment properties model. + */ +model ExperimentProperties { + /** + * Most recent provisioning state for the given experiment resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * List of steps. + */ + @identifiers(#["name"]) + steps: ChaosExperimentStep[]; + + /** + * List of selectors. + */ + selectors: ChaosTargetSelector[]; + + /** + * Optional customer-managed Storage account where Experiment schema will be stored. + */ + @removed(Microsoft.Chaos.Versions.v2025_01_01) + customerDataStorage?: CustomerDataStorageProperties; +} + +/** + * Model that represents a step in the Experiment resource. + */ +model ChaosExperimentStep { + /** + * String of the step name. + */ + @minLength(1) + name: string; + + /** + * List of branches. + */ + @identifiers(#["name"]) + branches: ChaosExperimentBranch[]; +} + +/** + * Model that represents a branch in the step. 9 total per experiment. + */ +model ChaosExperimentBranch { + /** + * String of the branch name. + */ + @minLength(1) + name: string; + + /** + * List of actions. + */ + @identifiers(#["name"]) + actions: ChaosExperimentAction[]; +} + +/** + * Model that represents the base action model. 9 total per experiment. + */ +@discriminator("type") +model ChaosExperimentAction { + /** + * String that represents a Capability URN. + */ + @maxLength(2048) + name: string; + + /** + * Chaos experiment action discriminator type + */ + type: ExperimentActionType; +} + +/** + * Model that represents a selector in the Experiment resource. + */ +@discriminator("type") +model ChaosTargetSelector { + /** + * String of the selector ID. + */ + @minLength(1) + id: string; + + /** + * Chaos target selector discriminator type + */ + type: SelectorType; + + /** + * Model that represents available filter types that can be applied to a targets list. + */ + filter?: ChaosTargetFilter; +} + +/** + * Model that represents available filter types that can be applied to a targets list. + */ +@discriminator("type") +model ChaosTargetFilter { + /** + * Chaos target filter discriminator type + */ + type: FilterType; +} + +/** + * Model that represents the Customer Managed Storage for an Experiment. + */ +model CustomerDataStorageProperties { + /** + * ARM Resource ID of the Storage account to use for Customer Data storage. + */ + storageAccountResourceId?: Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.Storage/storageAccounts"; + } + ]>; + + /** + * Name of the Azure Blob Storage container to use or create. + */ + @maxLength(63) + @minLength(3) + @pattern("^[a-z0-9]([a-z0-9]|(-(?!-))){1,61}[a-z0-9]$") + blobContainerName?: string; +} + +/** + * Describes an experiment update. + */ +model ExperimentUpdate { + ...Azure.ResourceManager.Foundations.TagsUpdateModel; + ...Azure.ResourceManager.ManagedServiceIdentityProperty; +} + +/** + * Model that represents a continuous action. + */ +model ContinuousAction extends ChaosExperimentAction { + /** + * ISO8601 formatted string that represents a duration. + */ + duration: duration; + + /** + * List of key value pairs. + */ + @identifiers(#["key"]) + parameters: KeyValuePair[]; + + /** + * String that represents a selector. + */ + @minLength(1) + selectorId: string; + + /** + * Enum that discriminates between action models. + */ + type: "continuous"; +} + +/** + * A map to describe the settings of an action. + */ +model KeyValuePair { + /** + * The name of the setting for the action. + */ + @minLength(1) + key: string; + + /** + * The value of the setting for the action. + */ + @minLength(1) + value: string; +} + +/** + * Model that represents a delay action. + */ +model DelayAction extends ChaosExperimentAction { + /** + * ISO8601 formatted string that represents a duration. + */ + duration: duration; + + /** + * Enum that discriminates between action models. + */ + type: "delay"; +} + +/** + * Model that represents a discrete action. + */ +model DiscreteAction extends ChaosExperimentAction { + /** + * List of key value pairs. + */ + @identifiers(#["key"]) + parameters: KeyValuePair[]; + + /** + * String that represents a selector. + */ + @minLength(1) + selectorId: string; + + /** + * Enum that discriminates between action models. + */ + type: "discrete"; +} + +/** + * Model that represents a list selector. + */ +model ChaosTargetListSelector extends ChaosTargetSelector { + /** + * List of Target references. + */ + targets: TargetReference[]; + + /** + * Enum of the selector type. + */ + type: "List"; +} + +/** + * Model that represents a reference to a Target in the selector. + */ +model TargetReference { + /** + * Enum of the Target reference type. + */ + type: TargetReferenceType; + + /** + * String of the resource ID of a Target resource. + */ + id: Azure.Core.armResourceIdentifier; +} + +/** + * Model that represents a query selector. + */ +model ChaosTargetQuerySelector extends ChaosTargetSelector { + /** + * Azure Resource Graph (ARG) Query Language query for target resources. + */ + queryString: string; + + /** + * Subscription id list to scope resource query. + */ + subscriptionIds: string[]; + + /** + * Enum of the selector type. + */ + type: "Query"; +} + +/** + * Model that represents a simple target filter. + */ +model ChaosTargetSimpleFilter extends ChaosTargetFilter { + /** + * Model that represents the Simple filter parameters. + */ + parameters?: ChaosTargetSimpleFilterParameters; + + /** + * Enum that discriminates between filter types. Currently only `Simple` type is supported. + */ + type: "Simple"; +} + +/** + * Model that represents the Simple filter parameters. + */ +model ChaosTargetSimpleFilterParameters { + /** + * List of Azure availability zones to filter targets by. + */ + zones?: string[]; +} diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/experiment.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/experiment.tsp new file mode 100644 index 00000000000..71067543f61 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/experiment.tsp @@ -0,0 +1,98 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./experiment.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +@armResourceOperations +interface Experiments { + /** + * Get a Experiment resource. + */ + get is ArmResourceRead; + + /** + * Create or update a Experiment resource. + */ + createOrUpdate is ArmResourceCreateOrReplaceAsync; + + /** + * The operation to update an experiment. + */ + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchAsync; + + /** + * Delete a Experiment resource. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Get a list of Experiment resources in a resource group. + */ + list is ArmResourceListByParent< + Experiment, + Parameters = { + /** + * Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then the results will not be filtered. + */ + @query("running") + running?: boolean; + + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = ExperimentListResult + >; + + /** + * Get a list of Experiment resources in a subscription. + */ + listAll is ArmListBySubscription< + Experiment, + Parameters = { + /** + * Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then the results will not be filtered. + */ + @query("running") + running?: boolean; + + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = ExperimentListResult + >; + + /** + * Cancel a running Experiment resource. + */ + cancel is ArmResourceActionNoResponseContentAsync; + + /** + * Start a Experiment resource. + */ + start is ArmResourceActionNoResponseContentAsync; +} + +@@minLength(Experiment.name, 1); +@@doc(Experiment.name, "String that represents a Experiment resource name."); +@@doc(Experiment.properties, "The properties of the experiment resource."); +@@doc(Experiments.createOrUpdate::parameters.resource, + "Experiment resource to be created or updated." +); +@@doc(Experiments.update::parameters.properties, + "Parameters supplied to the Update experiment operation." +); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/experimentExecution.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/experimentExecution.models.tsp new file mode 100644 index 00000000000..8417a86fd4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/experimentExecution.models.tsp @@ -0,0 +1,308 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./experiment.models.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.Chaos; + +/** + * Model that represents the execution of a Experiment. + */ +@parentResource(Experiment) +model ExperimentExecution + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = ExperimentExecution, + KeyName = "executionId", + SegmentName = "executions", + NamePattern = "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + >; +} + +/** + * Model that represents the execution properties of an Experiment. + */ +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "Unused property, avoids breaking changes in SDK." +model ExperimentExecutionProperties { + /** + * The status of the execution. + */ + @visibility(Lifecycle.Read) + status?: string; + + /** + * String that represents the start date time. + */ + @visibility(Lifecycle.Read) + startedAt?: utcDateTime; + + /** + * String that represents the stop date time. + */ + @visibility(Lifecycle.Read) + stoppedAt?: utcDateTime; + + /** + * Resource provisioning state. Not currently in use for executions. + */ + @removed(Microsoft.Chaos.Versions.v2025_01_01) + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Model that represents the execution details of an Experiment. + */ +model ExperimentExecutionDetails { + /** + * String of the resource type. + */ + @visibility(Lifecycle.Read) + type?: string; + + /** + * String of the fully qualified resource ID. + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * String of the resource name. + */ + @visibility(Lifecycle.Read) + name?: string; + + /** + * The properties of the experiment execution details. + */ + @visibility(Lifecycle.Read) + properties?: ExperimentExecutionDetailsProperties; +} + +/** + * Model that represents the extended properties of an experiment execution. + */ +#suppress "@azure-tools/typespec-azure-core/composition-over-inheritance" "For backward compatibility" +model ExperimentExecutionDetailsProperties { + /** + * The status of the execution. + */ + @visibility(Lifecycle.Read) + status?: string; + + /** + * String that represents the start date time. + */ + @visibility(Lifecycle.Read) + startedAt?: utcDateTime; + + /** + * String that represents the stop date time. + */ + @visibility(Lifecycle.Read) + stoppedAt?: utcDateTime; + + /** + * Resource provisioning state. Not currently in use for executions. + */ + @removed(Microsoft.Chaos.Versions.v2025_01_01) + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * The reason why the execution failed. + */ + @visibility(Lifecycle.Read) + failureReason?: string; + + /** + * String that represents the last action date time. + */ + @visibility(Lifecycle.Read) + lastActionAt?: utcDateTime; + + /** + * The information of the experiment run. + */ + @visibility(Lifecycle.Read) + runInformation?: ExperimentExecutionDetailsPropertiesRunInformation; +} + +/** + * The information of the experiment run. + */ +model ExperimentExecutionDetailsPropertiesRunInformation { + /** + * The steps of the experiment run. + */ + @visibility(Lifecycle.Read) + @identifiers(#["stepName"]) + steps?: StepStatus[]; +} + +/** + * Model that represents the a list of branches and branch statuses. + */ +model StepStatus { + /** + * The name of the step. + */ + @visibility(Lifecycle.Read) + stepName?: string; + + /** + * The id of the step. + */ + @visibility(Lifecycle.Read) + stepId?: string; + + /** + * The value of the status of the step. + */ + @visibility(Lifecycle.Read) + status?: string; + + /** + * The array of branches. + */ + @visibility(Lifecycle.Read) + @identifiers(#["branchName"]) + branches?: BranchStatus[]; +} + +/** + * Model that represents the a list of actions and action statuses. + */ +model BranchStatus { + /** + * The name of the branch status. + */ + @visibility(Lifecycle.Read) + branchName?: string; + + /** + * The id of the branch status. + */ + @visibility(Lifecycle.Read) + branchId?: string; + + /** + * The status of the branch. + */ + @visibility(Lifecycle.Read) + status?: string; + + /** + * The array of actions. + */ + @visibility(Lifecycle.Read) + @identifiers(#["actionId"]) + actions?: ActionStatus[]; +} + +/** + * Model that represents the an action and its status. + */ +model ActionStatus { + /** + * The name of the action status. + */ + @visibility(Lifecycle.Read) + actionName?: string; + + /** + * The id of the action status. + */ + @visibility(Lifecycle.Read) + actionId?: string; + + /** + * The status of the action. + */ + @visibility(Lifecycle.Read) + status?: string; + + /** + * String that represents the start time of the action. + */ + @visibility(Lifecycle.Read) + startTime?: utcDateTime; + + /** + * String that represents the end time of the action. + */ + @visibility(Lifecycle.Read) + endTime?: utcDateTime; + + /** + * The array of targets. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + targets?: ExperimentExecutionActionTargetDetailsProperties[]; +} + +/** + * Model that represents the Experiment action target details properties model. + */ +model ExperimentExecutionActionTargetDetailsProperties { + /** + * The status of the execution. + */ + @visibility(Lifecycle.Read) + status?: string; + + /** + * The target for the action. + */ + @visibility(Lifecycle.Read) + target?: string; + + /** + * String that represents the failed date time. + */ + @visibility(Lifecycle.Read) + targetFailedTime?: utcDateTime; + + /** + * String that represents the completed date time. + */ + @visibility(Lifecycle.Read) + targetCompletedTime?: utcDateTime; + + /** + * The error of the action. + */ + @visibility(Lifecycle.Read) + error?: ExperimentExecutionActionTargetDetailsError; +} + +/** + * Model that represents the Experiment action target details error model. + */ +model ExperimentExecutionActionTargetDetailsError { + /** + * The error code. + */ + @visibility(Lifecycle.Read) + code?: string; + + /** + * The error message + */ + @visibility(Lifecycle.Read) + message?: string; +} + +/** + * Model that represents a list of Experiment executions and a link for pagination. + */ +model ExperimentExecutionListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/experimentExecution.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/experimentExecution.tsp new file mode 100644 index 00000000000..151a2682915 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/experimentExecution.tsp @@ -0,0 +1,48 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./experiment.tsp"; +import "./experimentExecution.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +@armResourceOperations +interface ExperimentExecutions { + /** + * Get an execution of an Experiment resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + getExecution is ArmResourceRead; + + /** + * Get a list of executions of an Experiment resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + listAllExecutions is ArmResourceListByParent< + ExperimentExecution, + Response = ExperimentExecutionListResult + >; + + /** + * Execution details of an experiment resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + getExecutionDetails is ArmResourceActionSync< + ExperimentExecution, + void, + ExperimentExecutionDetails + >; +} + +@@doc(ExperimentExecution.name, + "GUID that represents a Experiment execution detail." +); +@@doc(ExperimentExecution.properties, + "The properties of experiment execution status." +); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/main.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/main.tsp new file mode 100644 index 00000000000..eb54d61ef2f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/main.tsp @@ -0,0 +1,54 @@ +/** + * PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS + * Generated by package: @autorest/openapi-to-typespec + * Version: 0.10.3 + * Date: 2024-11-25T19:03:17.069Z + */ +import "@typespec/rest"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./capability.tsp"; +import "./capabilityType.tsp"; +import "./experiment.tsp"; +import "./experimentExecution.tsp"; +import "./privateAccess.tsp"; +import "./privateEndpointConnection.tsp"; +import "./target.tsp"; +import "./targetType.tsp"; +import "./operationStatus.tsp"; +import "./back-compatible.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager.Foundations; +using Azure.Core; +using Azure.ResourceManager; +using TypeSpec.Versioning; +/** + * Chaos Management Client + */ +@armProviderNamespace +@service(#{ title: "ChaosManagementClient" }) +@versioned(Versions) +@armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v5) +namespace Microsoft.Chaos; + +/** + * The available API versions. + */ +enum Versions { + /** + * The 2024-11-01-preview API version. + */ + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(Azure.Core.Versions.v1_0_Preview_1) + v2024_11_01_preview: "2024-11-01-preview", + + /** + * The 2025-01-01 API version. + */ + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(Azure.Core.Versions.v1_0_Preview_1) + v2025_01_01: "2025-01-01", +} diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/operationStatus.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/operationStatus.tsp new file mode 100644 index 00000000000..5354d99a373 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/operationStatus.tsp @@ -0,0 +1,39 @@ +import "@azure-tools/typespec-azure-core"; +import "@typespec/rest"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "./common.models.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +/** + * Chaos Studio async operation status resource operations. + */ +@armResourceOperations +interface OperationStatuses { + /** + * Returns the current status of an async operation. + */ + @autoRoute + get( + ...ApiVersionParameter, + ...SubscriptionIdParameter, + + /** + * The provider namespace (this parameter will not show up in operations). + */ + @path + @segment("providers") + provider: "Microsoft.Chaos", + + ...LocationParameter, + ...Foundations.OperationIdParameter, + ): ArmResponse | ErrorResponse; +} + +@@segment(OperationStatuses.get::parameters.operationId, "operationStatuses"); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/privateAccess.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateAccess.models.tsp new file mode 100644 index 00000000000..fdcaa840e9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateAccess.models.tsp @@ -0,0 +1,79 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +/** + * PrivateAccesses tracked resource. + */ +model PrivateAccess + is Azure.ResourceManager.TrackedResource { + ...ResourceNameParameter< + Resource = PrivateAccess, + KeyName = "privateAccessName", + SegmentName = "privateAccesses", + NamePattern = "^[^<>%&:?#/\\\\]+$" + >; +} + +/** + * Describes a private access update. + */ +model PrivateAccessPatch { + /** + * The tags of the private access resource. + */ + ...Azure.ResourceManager.Foundations.TagsUpdateModel; +} + +/** + * The properties of a private access resource + */ +model PrivateAccessProperties { + /** + * Most recent provisioning state for the given privateAccess resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * A readonly collection of private endpoint connection. Currently only one endpoint connection is supported. + */ + @visibility(Lifecycle.Read) + privateEndpointConnections?: PrivateEndpointConnection[]; + + /** + * Public Network Access Control for PrivateAccess resource. + */ + publicNetworkAccess?: PublicNetworkAccessOption; +} + +/** + * Public Network Access Control for PrivateAccess resource. + */ +union PublicNetworkAccessOption { + string, + + /** + * Enabled access. + */ + Enabled: "Enabled", + + /** + * Disabled access. + */ + Disabled: "Disabled", +} + +/** + * Model that represents a list of private access resources and a link for pagination. + */ +model PrivateAccessListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/privateAccess.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateAccess.tsp new file mode 100644 index 00000000000..1df86ccf923 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateAccess.tsp @@ -0,0 +1,93 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./privateAccess.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.Chaos; + +@armResourceOperations +@removed(Microsoft.Chaos.Versions.v2025_01_01) +interface PrivateAccesses { + /** + * Get a private access resource + */ + get is ArmResourceRead; + + /** + * Create or update a private access + */ + createOrUpdate is ArmResourceCreateOrReplaceAsync; + + /** + * Patch a private access tags + */ + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchAsync; + + /** + * Delete a private access + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Get a list of private access resources in a resource group. + */ + list is ArmResourceListByParent< + PrivateAccess, + Parameters = { + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = PrivateAccessListResult + >; + + /** + * Get a list of private access resources in a subscription. + */ + listAll is ArmListBySubscription< + PrivateAccess, + Parameters = { + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = PrivateAccessListResult + >; + + /** + * Gets the private link resources possible under private access resource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + @get + privateLinkResources is ArmResourceActionSync< + PrivateAccess, + void, + PrivateLinkResourceListResult + >; +} + +@@minLength(PrivateAccess.name, 1); +@@doc(PrivateAccess.name, + "The name of the private access resource that is being created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 characters." +); +@@doc(PrivateAccess.properties, + "The resource-specific properties for this resource." +); +@@doc(PrivateAccesses.createOrUpdate::parameters.resource, + "private access resource to be created or updated." +); +@@doc(PrivateAccesses.update::parameters.properties, + "private access resource's tags to be updated." +); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/privateEndpointConnection.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateEndpointConnection.models.tsp new file mode 100644 index 00000000000..7bf7c8157bd --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateEndpointConnection.models.tsp @@ -0,0 +1,162 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./privateAccess.models.tsp"; +import "./common.models.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; +/** + * The private endpoint connection resource. + */ +@parentResource(PrivateAccess) +model PrivateEndpointConnection + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PrivateEndpointConnection, + KeyName = "privateEndpointConnectionName", + SegmentName = "privateEndpointConnections", + NamePattern = "^[^<>%&:?#/\\\\]+$" + >; +} + +/** + * Properties of the private endpoint connection. + */ +model PrivateEndpointConnectionProperties { + /** + * The group ids for the private endpoint resource. + */ + @visibility(Lifecycle.Read) + groupIds?: string[]; + + /** + * The private endpoint resource. + */ + privateEndpoint?: PrivateEndpoint; + + /** + * A collection of information about the state of the connection between service consumer and provider. + */ + privateLinkServiceConnectionState: PrivateLinkServiceConnectionState; + + /** + * The provisioning state of the private endpoint connection resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * The private endpoint resource. + */ +model PrivateEndpoint { + /** + * The ARM identifier for private endpoint. + */ + @visibility(Lifecycle.Read) + id?: string; +} + +/** + * A collection of information about the state of the connection between service consumer and provider. + */ +model PrivateLinkServiceConnectionState { + /** + * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + */ + status?: PrivateEndpointServiceConnectionStatus; + + /** + * The reason for approval/rejection of the connection. + */ + description?: string; + + /** + * A message indicating if changes on the service provider require any updates on the consumer. + */ + actionsRequired?: string; +} + +/** + * The private endpoint connection status. + */ +union PrivateEndpointServiceConnectionStatus { + string, + + /** + * Pending status. + */ + Pending: "Pending", + + /** + * Approved status. + */ + Approved: "Approved", + + /** + * Rejected status. + */ + Rejected: "Rejected", +} + +/** + * A list of private link resources + */ +model PrivateEndpointConnectionListResult + is Azure.Core.Page; + +/** + * A private link resource. + */ +model PrivateLinkResource + is Azure.ResourceManager.TrackedResource< + PrivateLinkResourceProperties, + false + > { + ...ResourceNameParameter< + Resource = PrivateLinkResource, + KeyName = "privateLinkName", + SegmentName = "privateLinkResources", + NamePattern = "^[^<>%&:?#/\\\\]+$" + >; +} + +/** + * Properties of a private link resource. + */ +model PrivateLinkResourceProperties { + /** + * The private link resource group id. + */ + @visibility(Lifecycle.Read) + groupId?: string; + + /** + * The private link resource required member names. + */ + @visibility(Lifecycle.Read) + requiredMembers?: string[]; + + /** + * The private link resource private link DNS zone name. + */ + requiredZoneNames?: string[]; + + /** + * Resource provisioning state. Not currently in use. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * A list of private link resources + */ +model PrivateLinkResourceListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/privateEndpointConnection.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateEndpointConnection.tsp new file mode 100644 index 00000000000..ccb5e28f49f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/privateEndpointConnection.tsp @@ -0,0 +1,44 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./privateEndpointConnection.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.Chaos; +@removed(Microsoft.Chaos.Versions.v2025_01_01) +@armResourceOperations +interface PrivateEndpointConnections { + /** + * Gets information about a private endpoint connection under a private access resource. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "Linting error - is actually camel-case." + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + getAPrivateEndpointConnection is ArmResourceRead; + + /** + * Deletes a private endpoint connection under a private access resource. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "Linting error - is actually camel-case." + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + deleteAPrivateEndpointConnection is ArmResourceDeleteWithoutOkAsync; + + /** + * List information about private endpoint connections under a private access resource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Required to not break existing SDKs" + listPrivateEndpointConnections is ArmResourceListByParent< + PrivateEndpointConnection, + Response = PrivateEndpointConnectionListResult + >; +} + +@@doc(PrivateEndpointConnection.name, + "The name of the private endpoint connection." +); +@@doc(PrivateEndpointConnection.properties, "Resource properties."); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/sdk-suppressions.yaml b/tests-upgrade/tests-emitter/Chaos.Management.brown/sdk-suppressions.yaml new file mode 100644 index 00000000000..fb6c2023bed --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/sdk-suppressions.yaml @@ -0,0 +1,85 @@ +suppressions: + azure-sdk-for-js: + - package: "@azure/arm-chaos" + breaking-changes: + - Class ChaosManagementClient has a new signature + - Class ChaosManagementClient no longer has parameter $host + - Class ChaosManagementClient no longer has parameter apiVersion + - Class ChaosManagementClient no longer has parameter subscriptionId + - Enum KnownOrigin no longer has value System + - Enum KnownOrigin no longer has value User + - Enum KnownOrigin no longer has value UserSystem + - Interface Capability no longer has parameter description + - Interface Capability no longer has parameter parametersSchema + - Interface Capability no longer has parameter publisher + - Interface Capability no longer has parameter systemData + - Interface Capability no longer has parameter targetType + - Interface Capability no longer has parameter urn + - Interface CapabilityType no longer has parameter azureRbacActions + - Interface CapabilityType no longer has parameter azureRbacDataActions + - Interface CapabilityType no longer has parameter description + - Interface CapabilityType no longer has parameter displayName + - Interface CapabilityType no longer has parameter kind + - Interface CapabilityType no longer has parameter location + - Interface CapabilityType no longer has parameter parametersSchema + - Interface CapabilityType no longer has parameter publisher + - Interface CapabilityType no longer has parameter runtimeProperties + - Interface CapabilityType no longer has parameter systemData + - Interface CapabilityType no longer has parameter targetType + - Interface CapabilityType no longer has parameter urn + - Interface ChaosManagementClientOptionalParams no longer has parameter $host + - Interface ChaosManagementClientOptionalParams no longer has parameter endpoint + - Interface Experiment has a new required parameter properties + - Interface Experiment no longer has parameter provisioningState + - Interface Experiment no longer has parameter selectors + - Interface Experiment no longer has parameter steps + - Interface Experiment no longer has parameter systemData + - Interface ExperimentExecution no longer has parameter id + - Interface ExperimentExecution no longer has parameter name + - Interface ExperimentExecution no longer has parameter startedAt + - Interface ExperimentExecution no longer has parameter status + - Interface ExperimentExecution no longer has parameter stoppedAt + - Interface ExperimentExecution no longer has parameter type + - Interface ExperimentExecutionDetails no longer has parameter failureReason + - Interface ExperimentExecutionDetails no longer has parameter lastActionAt + - Interface ExperimentExecutionDetails no longer has parameter runInformation + - Interface ExperimentExecutionDetails no longer has parameter startedAt + - Interface ExperimentExecutionDetails no longer has parameter status + - Interface ExperimentExecutionDetails no longer has parameter stoppedAt + - Interface ExperimentsCancelOptionalParams no longer has parameter resumeFrom + - Interface ExperimentsCreateOrUpdateOptionalParams no longer has parameter resumeFrom + - Interface ExperimentsDeleteOptionalParams no longer has parameter resumeFrom + - Interface ExperimentsStartOptionalParams no longer has parameter resumeFrom + - Interface ExperimentsUpdateOptionalParams no longer has parameter resumeFrom + - Interface Target no longer has parameter systemData + - Interface TargetType has a new required parameter properties + - Interface TargetType no longer has parameter description + - Interface TargetType no longer has parameter displayName + - Interface TargetType no longer has parameter location + - Interface TargetType no longer has parameter propertiesSchema + - Interface TargetType no longer has parameter resourceTypes + - Interface TargetType no longer has parameter systemData + - Removed function getContinuationToken + - Removed operation Experiments.beginCancel + - Removed operation Experiments.beginCancelAndWait + - Removed operation Experiments.beginCreateOrUpdate + - Removed operation Experiments.beginCreateOrUpdateAndWait + - Removed operation Experiments.beginDelete + - Removed operation Experiments.beginDeleteAndWait + - Removed operation Experiments.beginStart + - Removed operation Experiments.beginStartAndWait + - Removed operation Experiments.beginUpdate + - Removed operation Experiments.beginUpdateAndWait + - Removed operation Experiments.executionDetails + - Removed operation Experiments.getExecution + - Removed operation Experiments.listAllExecutions + - Removed operation Operations.listAll + - Type of parameter identity of interface Experiment is changed from ResourceIdentity to ManagedServiceIdentity + - Type of parameter identity of interface ExperimentUpdate is changed from ResourceIdentity to ManagedServiceIdentity + - Type of parameter info of interface ErrorAdditionalInfo is changed from Record to Record + - "Type of parameter properties of interface Target is changed from {\n [propertyName: string]: any;\n } to Record" + - "Type of parameter tags of interface ExperimentUpdate is changed from {\n [propertyName: string]: string;\n } to Record" + - "Type of parameter tags of interface TrackedResource is changed from {\n [propertyName: string]: string;\n } to Record" + - Type of parameter type of interface ChaosExperimentAction is changed from "delay" | "discrete" | "continuous" to ExperimentActionType + - Type of parameter type of interface ChaosTargetFilter is changed from "Simple" to FilterType + - Type of parameter type of interface ChaosTargetSelector is changed from "List" | "Query" to SelectorType \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/target.models.tsp new file mode 100644 index 00000000000..12dafee6a2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target.models.tsp @@ -0,0 +1,41 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./common.models.tsp"; +import "./capabilityType.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.Http; +using TypeSpec.OpenAPI; +using Azure.Core; + +namespace Microsoft.Chaos; + +/** + * Model that represents a Target resource. + */ +model Target is Azure.ResourceManager.ProxyResource, false> { + ...ResourceNameParameter< + Resource = Target, + KeyName = "targetName", + SegmentName = "targets", + NamePattern = "^[a-zA-Z0-9_\\-\\.]+$" + >; + + /** + * Azure resource location. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "Required to avoid SDK breaking change." + location?: azureLocation; +} + +alias TargetParentResourceParameters = BaseParameters & + ParentResourceParameters; + +/** + * Model that represents a list of Target resources and a link for pagination. + */ +model TargetListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/target.tsp new file mode 100644 index 00000000000..f329fd2b7ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target.tsp @@ -0,0 +1,58 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./target.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.Http; +using TypeSpec.OpenAPI; +using Azure.Core; + +namespace Microsoft.Chaos; + +@armResourceOperations +interface Targets { + /** + * Get a Target resource that extends a tracked regional resource. + */ + get is ArmResourceRead; + + /** + * Create or update a Target resource that extends a tracked regional resource. + */ + createOrUpdate is ArmResourceCreateOrReplaceSync< + Target, + TargetParentResourceParameters + >; + + /** + * Delete a Target resource that extends a tracked regional resource. + */ + delete is ArmResourceDeleteSync; + + /** + * Get a list of Target resources that extend a tracked regional resource. + */ + list is ArmResourceListByParent< + Target, + { + ...TargetParentResourceParameters; + + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = TargetListResult + >; +} + +@@doc(Target.name, "String that represents a Target resource name."); +@@doc(Target.properties, "The properties of the target resource."); +@@doc(Targets.createOrUpdate::parameters.resource, + "Target resource to be created or updated." +); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/.gitattributes b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.csproj b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.csproj new file mode 100644 index 00000000000..0128919cece --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.Chaos.private + false + Microsoft.Azure.PowerShell.Cmdlets.Chaos + true + false + ./bin + $(OutputPath) + Az.Chaos.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/Chaos.Management.brown/target/Az.Chaos.nuspec b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.nuspec new file mode 100644 index 00000000000..38f874867d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.nuspec @@ -0,0 +1,32 @@ + + + + Az.Chaos + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: Chaos cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule Chaos + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.psm1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.psm1 new file mode 100644 index 00000000000..41b3145234a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Az.Chaos.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.Chaos.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Properties/AssemblyInfo.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..c4a37509231 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// 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. + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: System.Reflection.AssemblyCompanyAttribute("Microsoft")] +[assembly: System.Reflection.AssemblyCopyrightAttribute("Copyright © Microsoft")] +[assembly: System.Reflection.AssemblyProductAttribute("Microsoft Azure PowerShell")] +[assembly: System.Reflection.AssemblyTitleAttribute("Microsoft Azure PowerShell - ChaosManagementClient")] +[assembly: System.Reflection.AssemblyFileVersionAttribute("0.1.0.0")] +[assembly: System.Reflection.AssemblyVersionAttribute("0.1.0.0")] +[assembly: System.Runtime.InteropServices.ComVisibleAttribute(false)] +[assembly: System.CLSCompliantAttribute(false)] \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/README.md new file mode 100644 index 00000000000..81550ea8e70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/README.md @@ -0,0 +1,24 @@ + +# Az.Chaos +This directory contains the PowerShell module for the Chaos 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.Chaos`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/build-module.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/build-module.ps1 new file mode 100644 index 00000000000..b8f4807e538 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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 -Force -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 -Force -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.Chaos.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.Chaos.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 -Force +} +$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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $internalFolder + +$psd1 = Join-Path $PSScriptRoot './Az.Chaos.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.Chaos' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @(@{modelName="Selector"; cmdletName=""}, @{modelName="Step"; cmdletName=""}, @{modelName="Branch"; cmdletName=""}, @{modelName="Action"; cmdletName=""}) +$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: Chaos cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue -Force + } + $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.Chaos.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 '../../../tools/BuildScripts/AdaptAutorestModule.ps1' + $afterBuildTasksArgs = ConvertFrom-Json '{"SubModuleName":"Az.Chaos","ModuleRootName":"$(root-module-name)"}' -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/Chaos.Management.brown/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..c2129f5d711 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/create-model-cmdlets.ps1 @@ -0,0 +1,263 @@ +# ---------------------------------------------------------------------------------- +# 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.Chaos' + } + $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}" + $Prefix = 'Az' + # remove duplicated module name + if ($ObjectType.StartsWith('Chaos')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'Chaos' + } + $OutputPath = Join-Path -ChildPath "New-${Prefix}${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] + 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-${Prefix}${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} { + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.ModelCmdletAttribute()] + [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/Chaos.Management.brown/target/custom/Az.Chaos.custom.psm1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/custom/Az.Chaos.custom.psm1 new file mode 100644 index 00000000000..7b25f5277fb --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/custom/Az.Chaos.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Chaos.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.Chaos.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/Chaos.Management.brown/target/custom/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/custom/README.md new file mode 100644 index 00000000000..01419bd8163 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.Chaos` 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.Chaos.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.Chaos` 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.Chaos.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.Chaos.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.Chaos`. 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.Chaos.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.Chaos.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.Chaos`. +- `Microsoft.Azure.PowerShell.Cmdlets.Chaos.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.Chaos`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/docs/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/docs/README.md new file mode 100644 index 00000000000..b8104b33146 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Chaos` 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.Chaos` 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/Chaos.Management.brown/target/examples/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/export-surface.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/export-surface.ps1 new file mode 100644 index 00000000000..3788d76a571 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.Chaos' +$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/Chaos.Management.brown/target/exports/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/exports/README.md new file mode 100644 index 00000000000..4e86c3bb057 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.Chaos`. No other cmdlets in this repository are directly exported. What that means is the `Az.Chaos` 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.Chaos.private.dll`) and from the `..\custom\Az.Chaos.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.Chaos.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/Chaos.Management.brown/target/generate-help.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generate-help.ps1 new file mode 100644 index 00000000000..b3c2bea8d6a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Chaos.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.Chaos.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..a1122f49e58 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos' +$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.Chaos.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/Chaos.Management.brown/target/generated/Module.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/Module.cs new file mode 100644 index 00000000000..1a5c7a98522 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient 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.Chaos.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.Chaos"; + + /// 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.Chaos"; + + /// 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.Chaos.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.Chaos.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.Chaos.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.ChaosManagementClient(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/ChaosManagementClient.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/ChaosManagementClient.cs new file mode 100644 index 00000000000..226fd76b580 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/ChaosManagementClient.cs @@ -0,0 +1,9074 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Low-level API implementation for the ChaosManagementClient service. + /// Chaos Management Client + /// + public partial class ChaosManagementClient + { + + /// update a Capability resource that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// Capability resource to be created or updated. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilitiesCreateOrUpdate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesCreateOrUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update a Capability resource that extends a Target resource. + /// + /// Capability resource to be created or updated. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilitiesCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + var capabilityName = _match.Groups["capabilityName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities/" + + capabilityName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesCreateOrUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update a Capability resource that extends a Target resource. + /// + /// Capability resource to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilitiesCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + var capabilityName = _match.Groups["capabilityName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities/" + + capabilityName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Capability resource that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// Json string supplied to the CapabilitiesCreateOrUpdate operation + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesCreateOrUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update a Capability resource that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// Json string supplied to the CapabilitiesCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Capability resource that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// Capability resource to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilitiesCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesCreateOrUpdateWithResult_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.Chaos.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 CapabilitiesCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilitiesCreateOrUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// Capability resource to be created or 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 CapabilitiesCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + await eventListener.AssertNotNull(nameof(capabilityName),capabilityName); + await eventListener.AssertRegEx(nameof(capabilityName), capabilityName, @"^[a-zA-Z0-9\-\.]+-\d\.\d$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a Capability that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesDelete(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a Capability that extends a Target resource. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + var capabilityName = _match.Groups["capabilityName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities/" + + capabilityName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilitiesDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource 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 CapabilitiesDelete_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + await eventListener.AssertNotNull(nameof(capabilityName),capabilityName); + await eventListener.AssertRegEx(nameof(capabilityName), capabilityName, @"^[a-zA-Z0-9\-\.]+-\d\.\d$"); + } + } + + /// Get a Capability resource that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesGet(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Capability resource that extends a Target 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesGetViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + var capabilityName = _match.Groups["capabilityName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities/" + + capabilityName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Capability resource that extends a Target resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + var capabilityName = _match.Groups["capabilityName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities/" + + capabilityName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a Capability resource that extends a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesGetWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities/" + + global::System.Uri.EscapeDataString(capabilityName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesGetWithResult_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.Chaos.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 CapabilitiesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 CapabilitiesGet_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that represents a Capability resource 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 CapabilitiesGet_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string capabilityName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + await eventListener.AssertNotNull(nameof(capabilityName),capabilityName); + await eventListener.AssertRegEx(nameof(capabilityName), capabilityName, @"^[a-zA-Z0-9\-\.]+-\d\.\d$"); + } + } + + /// Get a list of Capability resources that extend a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesList(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Capability resources that extend a Target resource. + /// + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesListViaIdentity(global::System.String viaIdentity, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilitiesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Capability resources that extend a Target resource. + /// + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesListViaIdentityWithResult(global::System.String viaIdentity, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)/capabilities$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "/capabilities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesListWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of Capability resources that extend a Target resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilitiesListWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "/capabilities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilitiesListWithResult_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.Chaos.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 CapabilitiesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 CapabilitiesList_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that sets the continuation token. + /// String that represents a Target resource 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 CapabilitiesList_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string continuationToken, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + } + } + + /// Get a Capability Type resource for given Target Type and location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that represents a Target Type resource name. + /// String that represents a Capability Type resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesGet(string subscriptionId, string location, string targetTypeName, string capabilityTypeName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes/" + + global::System.Uri.EscapeDataString(targetTypeName) + + "/capabilityTypes/" + + global::System.Uri.EscapeDataString(capabilityTypeName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilityTypesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Capability Type resource for given Target Type and location. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesGetViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes/(?[^/]+)/capabilityTypes/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var targetTypeName = _match.Groups["targetTypeName"].Value; + var capabilityTypeName = _match.Groups["capabilityTypeName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes/" + + targetTypeName + + "/capabilityTypes/" + + capabilityTypeName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilityTypesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Capability Type resource for given Target Type and location. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A + /// that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes/(?[^/]+)/capabilityTypes/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var targetTypeName = _match.Groups["targetTypeName"].Value; + var capabilityTypeName = _match.Groups["capabilityTypeName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes/" + + targetTypeName + + "/capabilityTypes/" + + capabilityTypeName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilityTypesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a Capability Type resource for given Target Type and location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that represents a Target Type resource name. + /// String that represents a Capability Type resource name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A + /// that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesGetWithResult(string subscriptionId, string location, string targetTypeName, string capabilityTypeName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes/" + + global::System.Uri.EscapeDataString(targetTypeName) + + "/capabilityTypes/" + + global::System.Uri.EscapeDataString(capabilityTypeName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilityTypesGetWithResult_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.Chaos.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 CapabilityTypesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityType.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 CapabilityTypesGet_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityType.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Azure region. + /// String that represents a Target Type resource name. + /// String that represents a Capability Type resource 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 CapabilityTypesGet_Validate(string subscriptionId, string location, string targetTypeName, string capabilityTypeName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(targetTypeName),targetTypeName); + await eventListener.AssertRegEx(nameof(targetTypeName), targetTypeName, @"^[a-zA-Z0-9_\-\.]+$"); + await eventListener.AssertNotNull(nameof(capabilityTypeName),capabilityTypeName); + await eventListener.AssertRegEx(nameof(capabilityTypeName), capabilityTypeName, @"^[a-zA-Z0-9\-\.]+-\d\.\d$"); + } + } + + /// Get a list of Capability Type resources for given Target Type and location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that represents a Target Type resource name. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesList(string subscriptionId, string location, string targetTypeName, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes/" + + global::System.Uri.EscapeDataString(targetTypeName) + + "/capabilityTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilityTypesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Capability Type resources for given Target Type and location. + /// + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesListViaIdentity(global::System.String viaIdentity, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes/(?[^/]+)/capabilityTypes$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var targetTypeName = _match.Groups["targetTypeName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes/" + + targetTypeName + + "/capabilityTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CapabilityTypesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Capability Type resources for given Target Type and location. + /// + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesListViaIdentityWithResult(global::System.String viaIdentity, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes/(?[^/]+)/capabilityTypes$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var targetTypeName = _match.Groups["targetTypeName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes/" + + targetTypeName + + "/capabilityTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilityTypesListWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of Capability Type resources for given Target Type and location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that represents a Target Type resource name. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CapabilityTypesListWithResult(string subscriptionId, string location, string targetTypeName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes/" + + global::System.Uri.EscapeDataString(targetTypeName) + + "/capabilityTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CapabilityTypesListWithResult_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.Chaos.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 CapabilityTypesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 CapabilityTypesList_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Azure region. + /// String that represents a Target Type resource name. + /// String that sets the continuation token. + /// 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 CapabilityTypesList_Validate(string subscriptionId, string location, string targetTypeName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(targetTypeName),targetTypeName); + await eventListener.AssertRegEx(nameof(targetTypeName), targetTypeName, @"^[a-zA-Z0-9_\-\.]+$"); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + + /// Cancel a running Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsCancel(string subscriptionId, string resourceGroupName, string experimentName, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/cancel" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsCancel_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Cancel a running Experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsCancelViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/cancel" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsCancel_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentsCancel_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource 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 ExperimentsCancel_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + } + } + + /// update a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Experiment resource to be created or 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.Chaos.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 ExperimentsCreateOrUpdate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Experiment resource. + /// + /// Experiment resource to be created or 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.Chaos.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 ExperimentsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Experiment resource. + /// + /// Experiment resource to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Json string supplied to the ExperimentsCreateOrUpdate 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string experimentName, 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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Json string supplied to the ExperimentsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string experimentName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Experiment resource to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsCreateOrUpdateWithResult_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.Chaos.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 ExperimentsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsCreateOrUpdate_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource name. + /// Experiment resource to be created or 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 ExperimentsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsDelete(string subscriptionId, string resourceGroupName, string experimentName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a Experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsDeleteViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsDelete_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.Chaos.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 ExperimentsDelete_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource 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 ExperimentsDelete_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + } + } + + /// Execution details of an experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// GUID that represents a Experiment execution detail. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsExecutionDetails(string subscriptionId, string resourceGroupName, string experimentName, string executionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/executions/" + + global::System.Uri.EscapeDataString(executionId) + + "/getExecutionDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsExecutionDetails_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Execution details of an experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsExecutionDetailsViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)/executions/(?[^/]+)$", 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.Chaos/experiments/{experimentName}/executions/{executionId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + var executionId = _match.Groups["executionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/executions/" + + executionId + + "/getExecutionDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsExecutionDetails_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Execution details of an experiment resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsExecutionDetailsViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)/executions/(?[^/]+)$", 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.Chaos/experiments/{experimentName}/executions/{executionId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + var executionId = _match.Groups["executionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/executions/" + + executionId + + "/getExecutionDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsExecutionDetailsWithResult_Call (request, eventListener,sender); + } + } + + /// Execution details of an experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// GUID that represents a Experiment execution detail. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsExecutionDetailsWithResult(string subscriptionId, string resourceGroupName, string experimentName, string executionId, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/executions/" + + global::System.Uri.EscapeDataString(executionId) + + "/getExecutionDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsExecutionDetailsWithResult_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.Chaos.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 ExperimentsExecutionDetailsWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetails.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsExecutionDetails_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetails.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource name. + /// GUID that represents a Experiment execution detail. + /// 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 ExperimentsExecutionDetails_Validate(string subscriptionId, string resourceGroupName, string experimentName, string executionId, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + await eventListener.AssertNotNull(nameof(executionId),executionId); + await eventListener.AssertRegEx(nameof(executionId), executionId, @"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"); + } + } + + /// Get a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGet(string subscriptionId, string resourceGroupName, string experimentName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get an execution of an Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// GUID that represents a Experiment execution detail. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetExecution(string subscriptionId, string resourceGroupName, string experimentName, string executionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/executions/" + + global::System.Uri.EscapeDataString(executionId) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsGetExecution_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get an execution of an Experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetExecutionViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)/executions/(?[^/]+)$", 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.Chaos/experiments/{experimentName}/executions/{executionId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + var executionId = _match.Groups["executionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/executions/" + + executionId + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsGetExecution_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get an execution of an Experiment resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetExecutionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)/executions/(?[^/]+)$", 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.Chaos/experiments/{experimentName}/executions/{executionId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + var executionId = _match.Groups["executionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/executions/" + + executionId + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsGetExecutionWithResult_Call (request, eventListener,sender); + } + } + + /// Get an execution of an Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// GUID that represents a Experiment execution detail. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetExecutionWithResult(string subscriptionId, string resourceGroupName, string experimentName, string executionId, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/executions/" + + global::System.Uri.EscapeDataString(executionId) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsGetExecutionWithResult_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.Chaos.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 ExperimentsGetExecutionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecution.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsGetExecution_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecution.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource name. + /// GUID that represents a Experiment execution detail. + /// 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 ExperimentsGetExecution_Validate(string subscriptionId, string resourceGroupName, string experimentName, string executionId, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + await eventListener.AssertNotNull(nameof(executionId),executionId); + await eventListener.AssertRegEx(nameof(executionId), executionId, @"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"); + } + } + + /// Get a Experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Experiment resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsGetWithResult(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsGetWithResult_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.Chaos.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 ExperimentsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsGet_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource 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 ExperimentsGet_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + } + } + + /// Get a list of Experiment resources in 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. + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsList(string subscriptionId, string resourceGroupName, bool? running, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Experiment resources in a subscription. + /// The ID of the target subscription. The value must be an UUID. + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAll(string subscriptionId, bool? running, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsListAll_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of executions of an Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllExecutions(string subscriptionId, string resourceGroupName, string experimentName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/executions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsListAllExecutions_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of executions of an Experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllExecutionsViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)/executions$", 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.Chaos/experiments/{experimentName}/executions'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/executions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsListAllExecutions_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of executions of an Experiment resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllExecutionsViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)/executions$", 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.Chaos/experiments/{experimentName}/executions'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/executions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsListAllExecutionsWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of executions of an Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllExecutionsWithResult(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/executions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsListAllExecutionsWithResult_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.Chaos.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 ExperimentsListAllExecutionsWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsListAllExecutions_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource 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 ExperimentsListAllExecutions_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + } + } + + /// Get a list of Experiment resources in a subscription. + /// + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllViaIdentity(global::System.String viaIdentity, bool? running, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/experiments$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/experiments'"); + } + + // 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.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsListAll_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Experiment resources in a subscription. + /// + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllViaIdentityWithResult(global::System.String viaIdentity, bool? running, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/experiments$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/experiments'"); + } + + // 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.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsListAllWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of Experiment resources in a subscription. + /// The ID of the target subscription. The value must be an UUID. + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListAllWithResult(string subscriptionId, bool? running, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsListAllWithResult_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.Chaos.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 ExperimentsListAllWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsListAll_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// 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 ExperimentsListAll_Validate(string subscriptionId, bool? running, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + + /// Get a list of Experiment resources in a resource group. + /// + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListViaIdentity(global::System.String viaIdentity, bool? running, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments$", 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.Chaos/experiments'"); + } + + // 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.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Experiment resources in a resource group. + /// + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListViaIdentityWithResult(global::System.String viaIdentity, bool? running, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments$", 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.Chaos/experiments'"); + } + + // 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.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsListWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of Experiment resources in 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. + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsListWithResult(string subscriptionId, string resourceGroupName, bool? running, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == running ? global::System.String.Empty : "running=" + global::System.Uri.EscapeDataString(running.ToString())) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsListWithResult_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.Chaos.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 ExperimentsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsList_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// Optional value that indicates whether to filter results based on if the Experiment is currently + /// running. If null, then the results will not be filtered. + /// String that sets the continuation token. + /// 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 ExperimentsList_Validate(string subscriptionId, string resourceGroupName, bool? running, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + + /// Start a Experiment resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsStart(string subscriptionId, string resourceGroupName, string experimentName, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "/start" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsStart_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Start a Experiment 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsStartViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "/start" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsStart_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentsStart_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource 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 ExperimentsStart_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + } + } + + /// The operation to update an experiment. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Parameters supplied to the Update experiment 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.Chaos.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 ExperimentsUpdate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// The operation to update an experiment. + /// + /// Parameters supplied to the Update experiment 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.Chaos.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 ExperimentsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// The operation to update an experiment. + /// + /// Parameters supplied to the Update experiment operation. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Chaos/experiments/(?[^/]+)$", 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.Chaos/experiments/{experimentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var experimentName = _match.Groups["experimentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Chaos/experiments/" + + experimentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// The operation to update an experiment. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Json string supplied to the ExperimentsUpdate 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string experimentName, 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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ExperimentsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// The operation to update an experiment. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Json string supplied to the ExperimentsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ExperimentsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string experimentName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// The operation to update an experiment. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// String that represents a Experiment resource name. + /// Parameters supplied to the Update experiment operation. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentsUpdateWithResult(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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.Chaos/experiments/" + + global::System.Uri.EscapeDataString(experimentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ExperimentsUpdateWithResult_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.Chaos.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 ExperimentsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 ExperimentsUpdate_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// String that represents a Experiment resource name. + /// Parameters supplied to the Update experiment operation. + /// 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 ExperimentsUpdate_Validate(string subscriptionId, string resourceGroupName, string experimentName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(experimentName),experimentName); + await eventListener.AssertMinimumLength(nameof(experimentName),experimentName,1); + + await eventListener.AssertRegEx(nameof(experimentName), experimentName, @"^[^<>%&:?#/\\]+$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Returns the current status of an async operation. + /// The ID of the target subscription. The value must be an UUID. + /// The location name. + /// The ID of an ongoing async 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationStatusesGet(string subscriptionId, string location, string operationId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/operationStatuses/" + + global::System.Uri.EscapeDataString(operationId) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationStatusesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Returns the current status of an async 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationStatusesGetViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/operationStatuses/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/operationStatuses/{operationId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var operationId = _match.Groups["operationId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/operationStatuses/" + + operationId + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationStatusesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Returns the current status of an async operation. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationStatusesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/operationStatuses/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/operationStatuses/{operationId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var operationId = _match.Groups["operationId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/operationStatuses/" + + operationId + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationStatusesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Returns the current status of an async operation. + /// The ID of the target subscription. The value must be an UUID. + /// The location name. + /// The ID of an ongoing async operation. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationStatusesGetWithResult(string subscriptionId, string location, string operationId, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/operationStatuses/" + + global::System.Uri.EscapeDataString(operationId) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationStatusesGetWithResult_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.Chaos.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 OperationStatusesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationStatusResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 OperationStatusesGet_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationStatusResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 location name. + /// The ID of an ongoing async operation. + /// 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 OperationStatusesGet_Validate(string subscriptionId, string location, string operationId, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(operationId),operationId); + await eventListener.AssertMinimumLength(nameof(operationId),operationId,1); + } + } + + /// 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.Chaos.Runtime.ISendAsync pipeline to 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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Chaos/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.ISendAsync pipeline to 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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Chaos/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Chaos/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Chaos/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.ISendAsync pipeline to 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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Chaos/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Chaos/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Chaos/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.ISendAsync pipeline to 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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Chaos/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// Get a Target Type resources for given location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that represents a Target Type resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesGet(string subscriptionId, string location, string targetTypeName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes/" + + global::System.Uri.EscapeDataString(targetTypeName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetTypesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Target Type resources for given location. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesGetViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var targetTypeName = _match.Groups["targetTypeName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes/" + + targetTypeName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetTypesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Target Type resources for given location. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + var targetTypeName = _match.Groups["targetTypeName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes/" + + targetTypeName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetTypesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a Target Type resources for given location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that represents a Target Type resource name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that + /// will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesGetWithResult(string subscriptionId, string location, string targetTypeName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes/" + + global::System.Uri.EscapeDataString(targetTypeName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetTypesGetWithResult_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.Chaos.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 TargetTypesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetType.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 TargetTypesGet_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetType.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Azure region. + /// String that represents a Target Type resource 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 TargetTypesGet_Validate(string subscriptionId, string location, string targetTypeName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(targetTypeName),targetTypeName); + await eventListener.AssertRegEx(nameof(targetTypeName), targetTypeName, @"^[a-zA-Z0-9_\-\.]+$"); + } + } + + /// Get a list of Target Type resources for given location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesList(string subscriptionId, string location, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetTypesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Target Type resources for given location. + /// + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesListViaIdentity(global::System.String viaIdentity, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetTypesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Target Type resources for given location. + /// + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesListViaIdentityWithResult(global::System.String viaIdentity, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Chaos/locations/(?[^/]+)/targetTypes$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Chaos/locations/" + + location + + "/targetTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetTypesListWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of Target Type resources for given location. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetTypesListWithResult(string subscriptionId, string location, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Chaos/locations/" + + global::System.Uri.EscapeDataString(location) + + "/targetTypes" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetTypesListWithResult_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.Chaos.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 TargetTypesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 TargetTypesList_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Azure region. + /// String that sets the continuation token. + /// 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 TargetTypesList_Validate(string subscriptionId, string location, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + + /// update a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// Target resource to be created or updated. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetsCreateOrUpdate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsCreateOrUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update a Target resource that extends a tracked regional resource. + /// + /// Target resource to be created or updated. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsCreateOrUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update a Target resource that extends a tracked regional resource. + /// + /// Target resource to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// Json string supplied to the TargetsCreateOrUpdate operation + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsCreateOrUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// Json string supplied to the TargetsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will + /// be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// Target resource to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsCreateOrUpdateWithResult_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.Chaos.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 TargetsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetsCreateOrUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// Target resource to be created or 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 TargetsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget body, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsDelete(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a Target resource that extends a tracked regional resource. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource 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 TargetsDelete_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + } + } + + /// Get a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsGet(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Target resource that extends a tracked regional 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.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsGetViaIdentity(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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Target resource that extends a tracked regional resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will + /// be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets/(?[^/]+)$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + var targetName = _match.Groups["targetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets/" + + targetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a Target resource that extends a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will + /// be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsGetWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets/" + + global::System.Uri.EscapeDataString(targetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsGetWithResult_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.Chaos.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 TargetsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 TargetsGet_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that represents a Target resource 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 TargetsGet_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string targetName, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(targetName),targetName); + await eventListener.AssertRegEx(nameof(targetName), targetName, @"^[a-zA-Z0-9_\-\.]+$"); + } + } + + /// Get a list of Target resources that extend a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsList(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Target resources that extend a tracked regional resource. + /// + /// String that sets the continuation token. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsListViaIdentity(global::System.String viaIdentity, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.TargetsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a list of Target resources that extend a tracked regional resource. + /// + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A + /// that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsListViaIdentityWithResult(global::System.String viaIdentity, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.Chaos/targets$", 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/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var parentProviderNamespace = _match.Groups["parentProviderNamespace"].Value; + var parentResourceType = _match.Groups["parentResourceType"].Value; + var parentResourceName = _match.Groups["parentResourceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + parentProviderNamespace + + "/" + + parentResourceType + + "/" + + parentResourceName + + "/providers/Microsoft.Chaos/targets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsListWithResult_Call (request, eventListener,sender); + } + } + + /// Get a list of Target resources that extend a tracked regional resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that sets the continuation token. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A + /// that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task TargetsListWithResult(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-01-01"; + // 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/" + + global::System.Uri.EscapeDataString(parentProviderNamespace) + + "/" + + global::System.Uri.EscapeDataString(parentResourceType) + + "/" + + global::System.Uri.EscapeDataString(parentResourceName) + + "/providers/Microsoft.Chaos/targets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.TargetsListWithResult_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.Chaos.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 TargetsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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 TargetsList_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.Chaos.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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. + /// The parent resource provider namespace. + /// The parent resource type. + /// The parent resource name. + /// String that sets the continuation token. + /// 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 TargetsList_Validate(string subscriptionId, string resourceGroupName, string parentProviderNamespace, string parentResourceType, string parentResourceName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(parentProviderNamespace),parentProviderNamespace); + await eventListener.AssertMaximumLength(nameof(parentProviderNamespace),parentProviderNamespace,63); + await eventListener.AssertRegEx(nameof(parentProviderNamespace), parentProviderNamespace, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceType),parentResourceType); + await eventListener.AssertMaximumLength(nameof(parentResourceType),parentResourceType,63); + await eventListener.AssertRegEx(nameof(parentResourceType), parentResourceType, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(parentResourceName),parentResourceName); + await eventListener.AssertMaximumLength(nameof(parentResourceName),parentResourceName,63); + await eventListener.AssertRegEx(nameof(parentResourceName), parentResourceName, @"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$"); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.PowerShell.cs new file mode 100644 index 00000000000..120737a3564 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the an action and its status. + [System.ComponentModel.TypeConverter(typeof(ActionStatusTypeConverter))] + public partial class ActionStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ActionStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ActionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionName = (string) content.GetValueForProperty("ActionName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionName, global::System.Convert.ToString); + } + if (content.Contains("ActionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionId = (string) content.GetValueForProperty("ActionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Target = (System.Collections.Generic.List) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Target, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsPropertiesTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ActionStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ActionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionName = (string) content.GetValueForProperty("ActionName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionName, global::System.Convert.ToString); + } + if (content.Contains("ActionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionId = (string) content.GetValueForProperty("ActionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).ActionId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Target = (System.Collections.Generic.List) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal)this).Target, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsPropertiesTypeConverter.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.Chaos.Models.IActionStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ActionStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ActionStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the an action and its status. + [System.ComponentModel.TypeConverter(typeof(ActionStatusTypeConverter))] + public partial interface IActionStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.TypeConverter.cs new file mode 100644 index 00000000000..3db7f5bfa89 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ActionStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IActionStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ActionStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ActionStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ActionStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ActionStatus.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.cs new file mode 100644 index 00000000000..df17cfba53f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the an action and its status. + public partial class ActionStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal + { + + /// Backing field for property. + private string _actionId; + + /// The id of the action status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ActionId { get => this._actionId; } + + /// Backing field for property. + private string _actionName; + + /// The name of the action status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ActionName { get => this._actionName; } + + /// Backing field for property. + private global::System.DateTime? _endTime; + + /// String that represents the end time of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? EndTime { get => this._endTime; } + + /// Internal Acessors for ActionId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal.ActionId { get => this._actionId; set { {_actionId = value;} } } + + /// Internal Acessors for ActionName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal.ActionName { get => this._actionName; set { {_actionName = value;} } } + + /// Internal Acessors for EndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal.EndTime { get => this._endTime; set { {_endTime = value;} } } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal.StartTime { get => this._startTime; set { {_startTime = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal.Status { get => this._status; set { {_status = value;} } } + + /// Internal Acessors for Target + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatusInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// String that represents the start time of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; } + + /// Backing field for property. + private string _status; + + /// The status of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Backing field for property. + private System.Collections.Generic.List _target; + + /// The array of targets. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Target { get => this._target; } + + /// Creates an new instance. + public ActionStatus() + { + + } + } + /// Model that represents the an action and its status. + public partial interface IActionStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The id of the action status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The id of the action status.", + SerializedName = @"actionId", + PossibleTypes = new [] { typeof(string) })] + string ActionId { get; } + /// The name of the action status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the action status.", + SerializedName = @"actionName", + PossibleTypes = new [] { typeof(string) })] + string ActionName { get; } + /// String that represents the end time of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the end time of the action.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; } + /// String that represents the start time of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the start time of the action.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// The status of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the action.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// The array of targets. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The array of targets.", + SerializedName = @"targets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties) })] + System.Collections.Generic.List Target { get; } + + } + /// Model that represents the an action and its status. + internal partial interface IActionStatusInternal + + { + /// The id of the action status. + string ActionId { get; set; } + /// The name of the action status. + string ActionName { get; set; } + /// String that represents the end time of the action. + global::System.DateTime? EndTime { get; set; } + /// String that represents the start time of the action. + global::System.DateTime? StartTime { get; set; } + /// The status of the action. + string Status { get; set; } + /// The array of targets. + System.Collections.Generic.List Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.json.cs new file mode 100644 index 00000000000..d4029a6ef16 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ActionStatus.json.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the an action and its status. + public partial class ActionStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ActionStatus(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_actionName = If( json?.PropertyT("actionName"), out var __jsonActionName) ? (string)__jsonActionName : (string)_actionName;} + {_actionId = If( json?.PropertyT("actionId"), out var __jsonActionId) ? (string)__jsonActionId : (string)_actionId;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? global::System.DateTime.TryParse((string)__jsonEndTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndTimeValue) ? __jsonEndTimeValue : _endTime : _endTime;} + {_target = If( json?.PropertyT("targets"), out var __jsonTargets) ? If( __jsonTargets as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsProperties.FromJson(__u) )) ))() : null : _target;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ActionStatus(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._actionName.ToString()) : null, "actionName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._actionId.ToString()) : null, "actionId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._endTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._endTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._target) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._target ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("targets",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..ccec820f5f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..26ba38e798d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..8e122f10ce8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..f4ec7aa668a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/BranchStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.PowerShell.cs new file mode 100644 index 00000000000..31de1964e67 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the a list of actions and action statuses. + [System.ComponentModel.TypeConverter(typeof(BranchStatusTypeConverter))] + public partial class BranchStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 BranchStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("BranchName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchName = (string) content.GetValueForProperty("BranchName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchName, global::System.Convert.ToString); + } + if (content.Contains("BranchId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchId = (string) content.GetValueForProperty("BranchId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Action")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Action = (System.Collections.Generic.List) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Action, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ActionStatusTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal BranchStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("BranchName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchName = (string) content.GetValueForProperty("BranchName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchName, global::System.Convert.ToString); + } + if (content.Contains("BranchId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchId = (string) content.GetValueForProperty("BranchId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).BranchId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Action")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Action = (System.Collections.Generic.List) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal)this).Action, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ActionStatusTypeConverter.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.Chaos.Models.IBranchStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new BranchStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new BranchStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the a list of actions and action statuses. + [System.ComponentModel.TypeConverter(typeof(BranchStatusTypeConverter))] + public partial interface IBranchStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.TypeConverter.cs new file mode 100644 index 00000000000..516481fc81d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class BranchStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IBranchStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return BranchStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return BranchStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return BranchStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/BranchStatus.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.cs new file mode 100644 index 00000000000..6aa434dc92d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the a list of actions and action statuses. + public partial class BranchStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _action; + + /// The array of actions. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Action { get => this._action; } + + /// Backing field for property. + private string _branchId; + + /// The id of the branch status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string BranchId { get => this._branchId; } + + /// Backing field for property. + private string _branchName; + + /// The name of the branch status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string BranchName { get => this._branchName; } + + /// Internal Acessors for Action + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal.Action { get => this._action; set { {_action = value;} } } + + /// Internal Acessors for BranchId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal.BranchId { get => this._branchId; set { {_branchId = value;} } } + + /// Internal Acessors for BranchName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal.BranchName { get => this._branchName; set { {_branchName = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatusInternal.Status { get => this._status; set { {_status = value;} } } + + /// Backing field for property. + private string _status; + + /// The status of the branch. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Creates an new instance. + public BranchStatus() + { + + } + } + /// Model that represents the a list of actions and action statuses. + public partial interface IBranchStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The array of actions. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The array of actions.", + SerializedName = @"actions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IActionStatus) })] + System.Collections.Generic.List Action { get; } + /// The id of the branch status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The id of the branch status.", + SerializedName = @"branchId", + PossibleTypes = new [] { typeof(string) })] + string BranchId { get; } + /// The name of the branch status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the branch status.", + SerializedName = @"branchName", + PossibleTypes = new [] { typeof(string) })] + string BranchName { get; } + /// The status of the branch. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the branch.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + + } + /// Model that represents the a list of actions and action statuses. + internal partial interface IBranchStatusInternal + + { + /// The array of actions. + System.Collections.Generic.List Action { get; set; } + /// The id of the branch status. + string BranchId { get; set; } + /// The name of the branch status. + string BranchName { get; set; } + /// The status of the branch. + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.json.cs new file mode 100644 index 00000000000..b2dbb2a7843 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/BranchStatus.json.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the a list of actions and action statuses. + public partial class BranchStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal BranchStatus(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_branchName = If( json?.PropertyT("branchName"), out var __jsonBranchName) ? (string)__jsonBranchName : (string)_branchName;} + {_branchId = If( json?.PropertyT("branchId"), out var __jsonBranchId) ? (string)__jsonBranchId : (string)_branchId;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_action = If( json?.PropertyT("actions"), out var __jsonActions) ? If( __jsonActions as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IActionStatus) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ActionStatus.FromJson(__u) )) ))() : null : _action;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new BranchStatus(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._branchName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._branchName.ToString()) : null, "branchName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._branchId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._branchId.ToString()) : null, "branchId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._action) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._action ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("actions",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.PowerShell.cs new file mode 100644 index 00000000000..db31305a109 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a Capability resource. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypeConverter))] + public partial class Capability + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 Capability(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.Chaos.Models.ICapabilityInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Urn, 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 Capability(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.Chaos.Models.ICapabilityInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal)this).Urn, 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.Chaos.Models.ICapability DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Capability(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Capability(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a Capability resource. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypeConverter))] + public partial interface ICapability + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.TypeConverter.cs new file mode 100644 index 00000000000..89e28a4c3a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapability ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Capability.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Capability.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Capability.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/Capability.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.cs new file mode 100644 index 00000000000..6bbb39b55e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Capability resource. + public partial class Capability : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(); + + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Description; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal.Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Description = value ?? null; } + + /// Internal Acessors for ParametersSchema + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal.ParametersSchema { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).ParametersSchema; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).ParametersSchema = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityProperties()); set { {_property = value;} } } + + /// Internal Acessors for Publisher + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal.Publisher { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Publisher; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Publisher = value ?? null; } + + /// Internal Acessors for TargetType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal.TargetType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).TargetType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).TargetType = value ?? null; } + + /// Internal Acessors for Urn + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityInternal.Urn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Urn; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Urn = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; } + + /// URL to retrieve JSON schema of the Capability parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string ParametersSchema { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).ParametersSchema; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties _property; + + /// The properties of a capability resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityProperties()); set => this._property = value; } + + /// String of the Publisher that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Publisher { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Publisher; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// String of the Target Type that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string TargetType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).TargetType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; } + + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Urn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)Property).Urn; } + + /// Creates an new instance. + public Capability() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Model that represents a Capability resource. + public partial interface ICapability : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource + { + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// URL to retrieve JSON schema of the Capability parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to retrieve JSON schema of the Capability parameters.", + SerializedName = @"parametersSchema", + PossibleTypes = new [] { typeof(string) })] + string ParametersSchema { get; } + /// String of the Publisher that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Publisher that this Capability extends.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + string Publisher { get; } + /// String of the Target Type that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Target Type that this Capability extends.", + SerializedName = @"targetType", + PossibleTypes = new [] { typeof(string) })] + string TargetType { get; } + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the URN for this Capability Type.", + SerializedName = @"urn", + PossibleTypes = new [] { typeof(string) })] + string Urn { get; } + + } + /// Model that represents a Capability resource. + internal partial interface ICapabilityInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResourceInternal + { + /// Localized string of the description. + string Description { get; set; } + /// URL to retrieve JSON schema of the Capability parameters. + string ParametersSchema { get; set; } + /// The properties of a capability resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties Property { get; set; } + /// String of the Publisher that this Capability extends. + string Publisher { get; set; } + /// String of the Target Type that this Capability extends. + string TargetType { get; set; } + /// String of the URN for this Capability Type. + string Urn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.json.cs new file mode 100644 index 00000000000..5cdbe9f6fb5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Capability.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Capability resource. + public partial class Capability + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal Capability(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new Capability(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.PowerShell.cs new file mode 100644 index 00000000000..87174afb161 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a list of Capability resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(CapabilityListResultTypeConverter))] + public partial class CapabilityListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CapabilityListResult(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.Chaos.Models.ICapabilityListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal)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 CapabilityListResult(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.Chaos.Models.ICapabilityListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal)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.Chaos.Models.ICapabilityListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CapabilityListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CapabilityListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a list of Capability resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(CapabilityListResultTypeConverter))] + public partial interface ICapabilityListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.TypeConverter.cs new file mode 100644 index 00000000000..0066d1d8b4e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapabilityListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CapabilityListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CapabilityListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CapabilityListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.cs new file mode 100644 index 00000000000..08e3fc51933 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list of Capability resources and a link for pagination. + public partial class CapabilityListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Capability items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public CapabilityListResult() + { + + } + } + /// Model that represents a list of Capability resources and a link for pagination. + public partial interface ICapabilityListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Capability items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Capability items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Model that represents a list of Capability resources and a link for pagination. + internal partial interface ICapabilityListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Capability items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.json.cs new file mode 100644 index 00000000000..e2a27e13b3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list of Capability resources and a link for pagination. + public partial class CapabilityListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal CapabilityListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ICapability) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability.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.Chaos.Models.ICapabilityListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new CapabilityListResult(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.PowerShell.cs new file mode 100644 index 00000000000..9b6a3e5897f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the Capability properties model. + [System.ComponentModel.TypeConverter(typeof(CapabilityPropertiesTypeConverter))] + public partial class CapabilityProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CapabilityProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Urn, 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 CapabilityProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal)this).Urn, 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.Chaos.Models.ICapabilityProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CapabilityProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CapabilityProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the Capability properties model. + [System.ComponentModel.TypeConverter(typeof(CapabilityPropertiesTypeConverter))] + public partial interface ICapabilityProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.TypeConverter.cs new file mode 100644 index 00000000000..3c34a4268b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapabilityProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CapabilityProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CapabilityProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CapabilityProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.cs new file mode 100644 index 00000000000..b2b22ccdb88 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Capability properties model. + public partial class CapabilityProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal + { + + /// Backing field for property. + private string _description; + + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for ParametersSchema + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal.ParametersSchema { get => this._parametersSchema; set { {_parametersSchema = value;} } } + + /// Internal Acessors for Publisher + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal.Publisher { get => this._publisher; set { {_publisher = value;} } } + + /// Internal Acessors for TargetType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal.TargetType { get => this._targetType; set { {_targetType = value;} } } + + /// Internal Acessors for Urn + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityPropertiesInternal.Urn { get => this._urn; set { {_urn = value;} } } + + /// Backing field for property. + private string _parametersSchema; + + /// URL to retrieve JSON schema of the Capability parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ParametersSchema { get => this._parametersSchema; } + + /// Backing field for property. + private string _publisher; + + /// String of the Publisher that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Publisher { get => this._publisher; } + + /// Backing field for property. + private string _targetType; + + /// String of the Target Type that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string TargetType { get => this._targetType; } + + /// Backing field for property. + private string _urn; + + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Urn { get => this._urn; } + + /// Creates an new instance. + public CapabilityProperties() + { + + } + } + /// Model that represents the Capability properties model. + public partial interface ICapabilityProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// URL to retrieve JSON schema of the Capability parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to retrieve JSON schema of the Capability parameters.", + SerializedName = @"parametersSchema", + PossibleTypes = new [] { typeof(string) })] + string ParametersSchema { get; } + /// String of the Publisher that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Publisher that this Capability extends.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + string Publisher { get; } + /// String of the Target Type that this Capability extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Target Type that this Capability extends.", + SerializedName = @"targetType", + PossibleTypes = new [] { typeof(string) })] + string TargetType { get; } + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the URN for this Capability Type.", + SerializedName = @"urn", + PossibleTypes = new [] { typeof(string) })] + string Urn { get; } + + } + /// Model that represents the Capability properties model. + internal partial interface ICapabilityPropertiesInternal + + { + /// Localized string of the description. + string Description { get; set; } + /// URL to retrieve JSON schema of the Capability parameters. + string ParametersSchema { get; set; } + /// String of the Publisher that this Capability extends. + string Publisher { get; set; } + /// String of the Target Type that this Capability extends. + string TargetType { get; set; } + /// String of the URN for this Capability Type. + string Urn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.json.cs new file mode 100644 index 00000000000..c019707d4ef --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityProperties.json.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Capability properties model. + public partial class CapabilityProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal CapabilityProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_publisher = If( json?.PropertyT("publisher"), out var __jsonPublisher) ? (string)__jsonPublisher : (string)_publisher;} + {_targetType = If( json?.PropertyT("targetType"), out var __jsonTargetType) ? (string)__jsonTargetType : (string)_targetType;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_parametersSchema = If( json?.PropertyT("parametersSchema"), out var __jsonParametersSchema) ? (string)__jsonParametersSchema : (string)_parametersSchema;} + {_urn = If( json?.PropertyT("urn"), out var __jsonUrn) ? (string)__jsonUrn : (string)_urn;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new CapabilityProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._publisher)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._publisher.ToString()) : null, "publisher" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._targetType.ToString()) : null, "targetType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._parametersSchema)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._parametersSchema.ToString()) : null, "parametersSchema" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._urn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._urn.ToString()) : null, "urn" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.PowerShell.cs new file mode 100644 index 00000000000..0063152afc9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.PowerShell.cs @@ -0,0 +1,338 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a Capability Type resource. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypeTypeConverter))] + public partial class CapabilityType + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CapabilityType(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.Chaos.Models.ICapabilityTypeInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("RuntimeProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimeProperty = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties) content.GetValueForProperty("RuntimeProperty",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimeProperty, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Urn, global::System.Convert.ToString); + } + if (content.Contains("Kind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Kind, global::System.Convert.ToString); + } + if (content.Contains("AzureRbacAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AzureRbacDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacDataAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacDataAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredAzureRoleDefinitionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RequiredAzureRoleDefinitionId = (System.Collections.Generic.List) content.GetValueForProperty("RequiredAzureRoleDefinitionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RequiredAzureRoleDefinitionId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RuntimePropertyKind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimePropertyKind = (string) content.GetValueForProperty("RuntimePropertyKind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimePropertyKind, 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 CapabilityType(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.Chaos.Models.ICapabilityTypeInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("RuntimeProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimeProperty = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties) content.GetValueForProperty("RuntimeProperty",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimeProperty, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Urn, global::System.Convert.ToString); + } + if (content.Contains("Kind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).Kind, global::System.Convert.ToString); + } + if (content.Contains("AzureRbacAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AzureRbacDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacDataAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).AzureRbacDataAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredAzureRoleDefinitionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RequiredAzureRoleDefinitionId = (System.Collections.Generic.List) content.GetValueForProperty("RequiredAzureRoleDefinitionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RequiredAzureRoleDefinitionId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RuntimePropertyKind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimePropertyKind = (string) content.GetValueForProperty("RuntimePropertyKind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal)this).RuntimePropertyKind, 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.Chaos.Models.ICapabilityType DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CapabilityType(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CapabilityType(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a Capability Type resource. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypeTypeConverter))] + public partial interface ICapabilityType + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.TypeConverter.cs new file mode 100644 index 00000000000..8af44111bc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityTypeTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapabilityType ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CapabilityType.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CapabilityType.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CapabilityType.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/CapabilityType.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.cs new file mode 100644 index 00000000000..6ff7847a102 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.cs @@ -0,0 +1,367 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Capability Type resource. + public partial class CapabilityType : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(); + + /// Control plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AzureRbacAction { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).AzureRbacAction; } + + /// Data plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AzureRbacDataAction { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).AzureRbacDataAction; } + + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Description; } + + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).DisplayName; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; } + + /// String of the kind of this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Kind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Kind; } + + /// Internal Acessors for AzureRbacAction + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.AzureRbacAction { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).AzureRbacAction; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).AzureRbacAction = value ?? null /* arrayOf */; } + + /// Internal Acessors for AzureRbacDataAction + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.AzureRbacDataAction { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).AzureRbacDataAction; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).AzureRbacDataAction = value ?? null /* arrayOf */; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Description = value ?? null; } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).DisplayName = value ?? null; } + + /// Internal Acessors for Kind + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.Kind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Kind; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Kind = value ?? null; } + + /// Internal Acessors for ParametersSchema + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.ParametersSchema { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).ParametersSchema; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).ParametersSchema = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeProperties()); set { {_property = value;} } } + + /// Internal Acessors for Publisher + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.Publisher { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Publisher; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Publisher = value ?? null; } + + /// Internal Acessors for RequiredAzureRoleDefinitionId + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.RequiredAzureRoleDefinitionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RequiredAzureRoleDefinitionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RequiredAzureRoleDefinitionId = value ?? null /* arrayOf */; } + + /// Internal Acessors for RuntimeProperty + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.RuntimeProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RuntimeProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RuntimeProperty = value ?? null /* model class */; } + + /// Internal Acessors for RuntimePropertyKind + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.RuntimePropertyKind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RuntimePropertyKind; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RuntimePropertyKind = value ?? null; } + + /// Internal Acessors for TargetType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.TargetType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).TargetType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).TargetType = value ?? null; } + + /// Internal Acessors for Urn + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeInternal.Urn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Urn; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Urn = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; } + + /// URL to retrieve JSON schema of the Capability Type parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string ParametersSchema { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).ParametersSchema; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties _property; + + /// The properties of the capability type resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeProperties()); set => this._property = value; } + + /// String of the Publisher that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Publisher { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Publisher; } + + /// Required Azure Role Definition Ids to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RequiredAzureRoleDefinitionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RequiredAzureRoleDefinitionId; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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); } + + /// String of the kind of the resource's action type (continuous or discrete). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string RuntimePropertyKind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).RuntimePropertyKind; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// String of the Target Type that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string TargetType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).TargetType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; } + + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Urn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)Property).Urn; } + + /// Creates an new instance. + public CapabilityType() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Model that represents a Capability Type resource. + public partial interface ICapabilityType : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource + { + /// Control plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Control plane actions necessary to execute capability type.", + SerializedName = @"azureRbacActions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AzureRbacAction { get; } + /// Data plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Data plane actions necessary to execute capability type.", + SerializedName = @"azureRbacDataActions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AzureRbacDataAction { get; } + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// String of the kind of this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the kind of this Capability Type.", + SerializedName = @"kind", + PossibleTypes = new [] { typeof(string) })] + string Kind { get; } + /// URL to retrieve JSON schema of the Capability Type parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to retrieve JSON schema of the Capability Type parameters.", + SerializedName = @"parametersSchema", + PossibleTypes = new [] { typeof(string) })] + string ParametersSchema { get; } + /// String of the Publisher that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Publisher that this Capability Type extends.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + string Publisher { get; } + /// Required Azure Role Definition Ids to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Required Azure Role Definition Ids to execute capability type.", + SerializedName = @"requiredAzureRoleDefinitionIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredAzureRoleDefinitionId { get; } + /// String of the kind of the resource's action type (continuous or discrete). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the kind of the resource's action type (continuous or discrete).", + SerializedName = @"kind", + PossibleTypes = new [] { typeof(string) })] + string RuntimePropertyKind { get; } + /// String of the Target Type that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Target Type that this Capability Type extends.", + SerializedName = @"targetType", + PossibleTypes = new [] { typeof(string) })] + string TargetType { get; } + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the URN for this Capability Type.", + SerializedName = @"urn", + PossibleTypes = new [] { typeof(string) })] + string Urn { get; } + + } + /// Model that represents a Capability Type resource. + internal partial interface ICapabilityTypeInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResourceInternal + { + /// Control plane actions necessary to execute capability type. + System.Collections.Generic.List AzureRbacAction { get; set; } + /// Data plane actions necessary to execute capability type. + System.Collections.Generic.List AzureRbacDataAction { get; set; } + /// Localized string of the description. + string Description { get; set; } + /// Localized string of the display name. + string DisplayName { get; set; } + /// String of the kind of this Capability Type. + string Kind { get; set; } + /// URL to retrieve JSON schema of the Capability Type parameters. + string ParametersSchema { get; set; } + /// The properties of the capability type resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties Property { get; set; } + /// String of the Publisher that this Capability Type extends. + string Publisher { get; set; } + /// Required Azure Role Definition Ids to execute capability type. + System.Collections.Generic.List RequiredAzureRoleDefinitionId { get; set; } + /// Runtime properties of this Capability Type. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties RuntimeProperty { get; set; } + /// String of the kind of the resource's action type (continuous or discrete). + string RuntimePropertyKind { get; set; } + /// String of the Target Type that this Capability Type extends. + string TargetType { get; set; } + /// String of the URN for this Capability Type. + string Urn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.json.cs new file mode 100644 index 00000000000..7fcbaf93ca9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityType.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Capability Type resource. + public partial class CapabilityType + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal CapabilityType(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new CapabilityType(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.PowerShell.cs new file mode 100644 index 00000000000..2b5133e4bc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// Model that represents a list of Capability Type resources and a link for pagination. + /// + [System.ComponentModel.TypeConverter(typeof(CapabilityTypeListResultTypeConverter))] + public partial class CapabilityTypeListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CapabilityTypeListResult(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.Chaos.Models.ICapabilityTypeListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal)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 CapabilityTypeListResult(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.Chaos.Models.ICapabilityTypeListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypeTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal)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.Chaos.Models.ICapabilityTypeListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CapabilityTypeListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CapabilityTypeListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a list of Capability Type resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypeListResultTypeConverter))] + public partial interface ICapabilityTypeListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.TypeConverter.cs new file mode 100644 index 00000000000..be9a3708473 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityTypeListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapabilityTypeListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CapabilityTypeListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CapabilityTypeListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CapabilityTypeListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.cs new file mode 100644 index 00000000000..141eb8a6ceb --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents a list of Capability Type resources and a link for pagination. + /// + public partial class CapabilityTypeListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The CapabilityType items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public CapabilityTypeListResult() + { + + } + } + /// Model that represents a list of Capability Type resources and a link for pagination. + public partial interface ICapabilityTypeListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 CapabilityType items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The CapabilityType items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Model that represents a list of Capability Type resources and a link for pagination. + internal partial interface ICapabilityTypeListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The CapabilityType items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.json.cs new file mode 100644 index 00000000000..df846dc1898 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents a list of Capability Type resources and a link for pagination. + /// + public partial class CapabilityTypeListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal CapabilityTypeListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ICapabilityType) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityType.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.Chaos.Models.ICapabilityTypeListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new CapabilityTypeListResult(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.PowerShell.cs new file mode 100644 index 00000000000..15c5aa9d136 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the Capability Type properties model. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypePropertiesTypeConverter))] + public partial class CapabilityTypeProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CapabilityTypeProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RuntimeProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimeProperty = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties) content.GetValueForProperty("RuntimeProperty",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimeProperty, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Urn, global::System.Convert.ToString); + } + if (content.Contains("Kind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Kind, global::System.Convert.ToString); + } + if (content.Contains("AzureRbacAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AzureRbacDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacDataAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacDataAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredAzureRoleDefinitionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RequiredAzureRoleDefinitionId = (System.Collections.Generic.List) content.GetValueForProperty("RequiredAzureRoleDefinitionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RequiredAzureRoleDefinitionId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RuntimePropertyKind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimePropertyKind = (string) content.GetValueForProperty("RuntimePropertyKind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimePropertyKind, 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 CapabilityTypeProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RuntimeProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimeProperty = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties) content.GetValueForProperty("RuntimeProperty",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimeProperty, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Publisher")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Publisher, global::System.Convert.ToString); + } + if (content.Contains("TargetType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).TargetType = (string) content.GetValueForProperty("TargetType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).TargetType, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ParametersSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).ParametersSchema = (string) content.GetValueForProperty("ParametersSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).ParametersSchema, global::System.Convert.ToString); + } + if (content.Contains("Urn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Urn = (string) content.GetValueForProperty("Urn",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Urn, global::System.Convert.ToString); + } + if (content.Contains("Kind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).Kind, global::System.Convert.ToString); + } + if (content.Contains("AzureRbacAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AzureRbacDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacDataAction = (System.Collections.Generic.List) content.GetValueForProperty("AzureRbacDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).AzureRbacDataAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredAzureRoleDefinitionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RequiredAzureRoleDefinitionId = (System.Collections.Generic.List) content.GetValueForProperty("RequiredAzureRoleDefinitionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RequiredAzureRoleDefinitionId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RuntimePropertyKind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimePropertyKind = (string) content.GetValueForProperty("RuntimePropertyKind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal)this).RuntimePropertyKind, 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.Chaos.Models.ICapabilityTypeProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CapabilityTypeProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CapabilityTypeProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the Capability Type properties model. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypePropertiesTypeConverter))] + public partial interface ICapabilityTypeProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.TypeConverter.cs new file mode 100644 index 00000000000..c6b6696a751 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityTypePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapabilityTypeProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CapabilityTypeProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CapabilityTypeProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CapabilityTypeProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.cs new file mode 100644 index 00000000000..a5650efd8eb --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.cs @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Capability Type properties model. + public partial class CapabilityTypeProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _azureRbacAction; + + /// Control plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List AzureRbacAction { get => this._azureRbacAction; } + + /// Backing field for property. + private System.Collections.Generic.List _azureRbacDataAction; + + /// Data plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List AzureRbacDataAction { get => this._azureRbacDataAction; } + + /// Backing field for property. + private string _description; + + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Backing field for property. + private string _displayName; + + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; } + + /// Backing field for property. + private string _kind; + + /// String of the kind of this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Kind { get => this._kind; } + + /// Internal Acessors for AzureRbacAction + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.AzureRbacAction { get => this._azureRbacAction; set { {_azureRbacAction = value;} } } + + /// Internal Acessors for AzureRbacDataAction + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.AzureRbacDataAction { get => this._azureRbacDataAction; set { {_azureRbacDataAction = value;} } } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.DisplayName { get => this._displayName; set { {_displayName = value;} } } + + /// Internal Acessors for Kind + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.Kind { get => this._kind; set { {_kind = value;} } } + + /// Internal Acessors for ParametersSchema + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.ParametersSchema { get => this._parametersSchema; set { {_parametersSchema = value;} } } + + /// Internal Acessors for Publisher + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.Publisher { get => this._publisher; set { {_publisher = value;} } } + + /// Internal Acessors for RequiredAzureRoleDefinitionId + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.RequiredAzureRoleDefinitionId { get => this._requiredAzureRoleDefinitionId; set { {_requiredAzureRoleDefinitionId = value;} } } + + /// Internal Acessors for RuntimeProperty + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.RuntimeProperty { get => (this._runtimeProperty = this._runtimeProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimeProperties()); set { {_runtimeProperty = value;} } } + + /// Internal Acessors for RuntimePropertyKind + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.RuntimePropertyKind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)RuntimeProperty).Kind; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)RuntimeProperty).Kind = value ?? null; } + + /// Internal Acessors for TargetType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.TargetType { get => this._targetType; set { {_targetType = value;} } } + + /// Internal Acessors for Urn + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesInternal.Urn { get => this._urn; set { {_urn = value;} } } + + /// Backing field for property. + private string _parametersSchema; + + /// URL to retrieve JSON schema of the Capability Type parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ParametersSchema { get => this._parametersSchema; } + + /// Backing field for property. + private string _publisher; + + /// String of the Publisher that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Publisher { get => this._publisher; } + + /// Backing field for property. + private System.Collections.Generic.List _requiredAzureRoleDefinitionId; + + /// Required Azure Role Definition Ids to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List RequiredAzureRoleDefinitionId { get => this._requiredAzureRoleDefinitionId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties _runtimeProperty; + + /// Runtime properties of this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties RuntimeProperty { get => (this._runtimeProperty = this._runtimeProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimeProperties()); } + + /// String of the kind of the resource's action type (continuous or discrete). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string RuntimePropertyKind { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)RuntimeProperty).Kind; } + + /// Backing field for property. + private string _targetType; + + /// String of the Target Type that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string TargetType { get => this._targetType; } + + /// Backing field for property. + private string _urn; + + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Urn { get => this._urn; } + + /// Creates an new instance. + public CapabilityTypeProperties() + { + + } + } + /// Model that represents the Capability Type properties model. + public partial interface ICapabilityTypeProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// Control plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Control plane actions necessary to execute capability type.", + SerializedName = @"azureRbacActions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AzureRbacAction { get; } + /// Data plane actions necessary to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Data plane actions necessary to execute capability type.", + SerializedName = @"azureRbacDataActions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AzureRbacDataAction { get; } + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// String of the kind of this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the kind of this Capability Type.", + SerializedName = @"kind", + PossibleTypes = new [] { typeof(string) })] + string Kind { get; } + /// URL to retrieve JSON schema of the Capability Type parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to retrieve JSON schema of the Capability Type parameters.", + SerializedName = @"parametersSchema", + PossibleTypes = new [] { typeof(string) })] + string ParametersSchema { get; } + /// String of the Publisher that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Publisher that this Capability Type extends.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + string Publisher { get; } + /// Required Azure Role Definition Ids to execute capability type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Required Azure Role Definition Ids to execute capability type.", + SerializedName = @"requiredAzureRoleDefinitionIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredAzureRoleDefinitionId { get; } + /// String of the kind of the resource's action type (continuous or discrete). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the kind of the resource's action type (continuous or discrete).", + SerializedName = @"kind", + PossibleTypes = new [] { typeof(string) })] + string RuntimePropertyKind { get; } + /// String of the Target Type that this Capability Type extends. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the Target Type that this Capability Type extends.", + SerializedName = @"targetType", + PossibleTypes = new [] { typeof(string) })] + string TargetType { get; } + /// String of the URN for this Capability Type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the URN for this Capability Type.", + SerializedName = @"urn", + PossibleTypes = new [] { typeof(string) })] + string Urn { get; } + + } + /// Model that represents the Capability Type properties model. + internal partial interface ICapabilityTypePropertiesInternal + + { + /// Control plane actions necessary to execute capability type. + System.Collections.Generic.List AzureRbacAction { get; set; } + /// Data plane actions necessary to execute capability type. + System.Collections.Generic.List AzureRbacDataAction { get; set; } + /// Localized string of the description. + string Description { get; set; } + /// Localized string of the display name. + string DisplayName { get; set; } + /// String of the kind of this Capability Type. + string Kind { get; set; } + /// URL to retrieve JSON schema of the Capability Type parameters. + string ParametersSchema { get; set; } + /// String of the Publisher that this Capability Type extends. + string Publisher { get; set; } + /// Required Azure Role Definition Ids to execute capability type. + System.Collections.Generic.List RequiredAzureRoleDefinitionId { get; set; } + /// Runtime properties of this Capability Type. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties RuntimeProperty { get; set; } + /// String of the kind of the resource's action type (continuous or discrete). + string RuntimePropertyKind { get; set; } + /// String of the Target Type that this Capability Type extends. + string TargetType { get; set; } + /// String of the URN for this Capability Type. + string Urn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.json.cs new file mode 100644 index 00000000000..61644097840 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypeProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Capability Type properties model. + public partial class CapabilityTypeProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal CapabilityTypeProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_runtimeProperty = If( json?.PropertyT("runtimeProperties"), out var __jsonRuntimeProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.CapabilityTypePropertiesRuntimeProperties.FromJson(__jsonRuntimeProperties) : _runtimeProperty;} + {_publisher = If( json?.PropertyT("publisher"), out var __jsonPublisher) ? (string)__jsonPublisher : (string)_publisher;} + {_targetType = If( json?.PropertyT("targetType"), out var __jsonTargetType) ? (string)__jsonTargetType : (string)_targetType;} + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_parametersSchema = If( json?.PropertyT("parametersSchema"), out var __jsonParametersSchema) ? (string)__jsonParametersSchema : (string)_parametersSchema;} + {_urn = If( json?.PropertyT("urn"), out var __jsonUrn) ? (string)__jsonUrn : (string)_urn;} + {_kind = If( json?.PropertyT("kind"), out var __jsonKind) ? (string)__jsonKind : (string)_kind;} + {_azureRbacAction = If( json?.PropertyT("azureRbacActions"), out var __jsonAzureRbacActions) ? If( __jsonAzureRbacActions as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _azureRbacAction;} + {_azureRbacDataAction = If( json?.PropertyT("azureRbacDataActions"), out var __jsonAzureRbacDataActions) ? If( __jsonAzureRbacDataActions as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(string) (__p is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString __o ? (string)(__o.ToString()) : null)) ))() : null : _azureRbacDataAction;} + {_requiredAzureRoleDefinitionId = If( json?.PropertyT("requiredAzureRoleDefinitionIds"), out var __jsonRequiredAzureRoleDefinitionIds) ? If( __jsonRequiredAzureRoleDefinitionIds as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(string) (__k is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString __j ? (string)(__j.ToString()) : null)) ))() : null : _requiredAzureRoleDefinitionId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypeProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new CapabilityTypeProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._runtimeProperty ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._runtimeProperty.ToJson(null,serializationMode) : null, "runtimeProperties" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._publisher)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._publisher.ToString()) : null, "publisher" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._targetType.ToString()) : null, "targetType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._parametersSchema)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._parametersSchema.ToString()) : null, "parametersSchema" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._urn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._urn.ToString()) : null, "urn" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._kind)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._kind.ToString()) : null, "kind" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._azureRbacAction) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._azureRbacAction ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("azureRbacActions",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._azureRbacDataAction) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __s in this._azureRbacDataAction ) + { + AddIf(null != (((object)__s)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(__s.ToString()) : null ,__r.Add); + } + container.Add("azureRbacDataActions",__r); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._requiredAzureRoleDefinitionId) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __n in this._requiredAzureRoleDefinitionId ) + { + AddIf(null != (((object)__n)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(__n.ToString()) : null ,__m.Add); + } + container.Add("requiredAzureRoleDefinitionIds",__m); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.PowerShell.cs new file mode 100644 index 00000000000..b4315cc612d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Runtime properties of this Capability Type. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypePropertiesRuntimePropertiesTypeConverter))] + public partial class CapabilityTypePropertiesRuntimeProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CapabilityTypePropertiesRuntimeProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Kind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)this).Kind, 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 CapabilityTypePropertiesRuntimeProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Kind")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal)this).Kind, 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.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CapabilityTypePropertiesRuntimeProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CapabilityTypePropertiesRuntimeProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Runtime properties of this Capability Type. + [System.ComponentModel.TypeConverter(typeof(CapabilityTypePropertiesRuntimePropertiesTypeConverter))] + public partial interface ICapabilityTypePropertiesRuntimeProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.TypeConverter.cs new file mode 100644 index 00000000000..c45639e8fb6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CapabilityTypePropertiesRuntimePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CapabilityTypePropertiesRuntimeProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CapabilityTypePropertiesRuntimeProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CapabilityTypePropertiesRuntimeProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.cs new file mode 100644 index 00000000000..a911f027591 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Runtime properties of this Capability Type. + public partial class CapabilityTypePropertiesRuntimeProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal + { + + /// Backing field for property. + private string _kind; + + /// String of the kind of the resource's action type (continuous or discrete). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Kind { get => this._kind; } + + /// Internal Acessors for Kind + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimePropertiesInternal.Kind { get => this._kind; set { {_kind = value;} } } + + /// + /// Creates an new instance. + /// + public CapabilityTypePropertiesRuntimeProperties() + { + + } + } + /// Runtime properties of this Capability Type. + public partial interface ICapabilityTypePropertiesRuntimeProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// String of the kind of the resource's action type (continuous or discrete). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the kind of the resource's action type (continuous or discrete).", + SerializedName = @"kind", + PossibleTypes = new [] { typeof(string) })] + string Kind { get; } + + } + /// Runtime properties of this Capability Type. + internal partial interface ICapabilityTypePropertiesRuntimePropertiesInternal + + { + /// String of the kind of the resource's action type (continuous or discrete). + string Kind { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.json.cs new file mode 100644 index 00000000000..4c2cd6cb33a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/CapabilityTypePropertiesRuntimeProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Runtime properties of this Capability Type. + public partial class CapabilityTypePropertiesRuntimeProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal CapabilityTypePropertiesRuntimeProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_kind = If( json?.PropertyT("kind"), out var __jsonKind) ? (string)__jsonKind : (string)_kind;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityTypePropertiesRuntimeProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new CapabilityTypePropertiesRuntimeProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._kind)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._kind.ToString()) : null, "kind" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.PowerShell.cs new file mode 100644 index 00000000000..3b8a64d1327 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the base action model. 9 total per experiment. + [System.ComponentModel.TypeConverter(typeof(ChaosExperimentActionTypeConverter))] + public partial class ChaosExperimentAction + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosExperimentAction(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.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)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 ChaosExperimentAction(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.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosExperimentAction(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosExperimentAction(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the base action model. 9 total per experiment. + [System.ComponentModel.TypeConverter(typeof(ChaosExperimentActionTypeConverter))] + public partial interface IChaosExperimentAction + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.TypeConverter.cs new file mode 100644 index 00000000000..896707e8385 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosExperimentActionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosExperimentAction ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosExperimentAction.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosExperimentAction.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosExperimentAction.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.cs new file mode 100644 index 00000000000..c5230ed071f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the base action model. 9 total per experiment. + public partial class ChaosExperimentAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal + { + + /// Backing field for property. + private string _name; + + /// String that represents a Capability URN. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _type; + + /// Chaos experiment action discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public ChaosExperimentAction() + { + + } + } + /// Model that represents the base action model. 9 total per experiment. + public partial interface IChaosExperimentAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// String that represents a Capability URN. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a Capability URN.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// Chaos experiment action discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Chaos experiment action discriminator type", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("delay", "discrete", "continuous")] + string Type { get; set; } + + } + /// Model that represents the base action model. 9 total per experiment. + internal partial interface IChaosExperimentActionInternal + + { + /// String that represents a Capability URN. + string Name { get; set; } + /// Chaos experiment action discriminator type + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("delay", "discrete", "continuous")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.json.cs new file mode 100644 index 00000000000..5bfba2e25c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentAction.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the base action model. 9 total per experiment. + public partial class ChaosExperimentAction + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosExperimentAction(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction interface is polymorphic, and the precise + /// model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("type") ) + { + case "continuous": + { + return new ContinuousAction(json); + } + case "delay": + { + return new DelayAction(json); + } + case "discrete": + { + return new DiscreteAction(json); + } + } + return new ChaosExperimentAction(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.PowerShell.cs new file mode 100644 index 00000000000..c34d44e89eb --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a branch in the step. 9 total per experiment. + [System.ComponentModel.TypeConverter(typeof(ChaosExperimentBranchTypeConverter))] + public partial class ChaosExperimentBranch + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosExperimentBranch(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.Chaos.Models.IChaosExperimentBranchInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Action")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal)this).Action = (System.Collections.Generic.List) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal)this).Action, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentActionTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ChaosExperimentBranch(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.Chaos.Models.IChaosExperimentBranchInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Action")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal)this).Action = (System.Collections.Generic.List) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal)this).Action, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentActionTypeConverter.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.Chaos.Models.IChaosExperimentBranch DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosExperimentBranch(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosExperimentBranch(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a branch in the step. 9 total per experiment. + [System.ComponentModel.TypeConverter(typeof(ChaosExperimentBranchTypeConverter))] + public partial interface IChaosExperimentBranch + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.TypeConverter.cs new file mode 100644 index 00000000000..e5cb87cbeb4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosExperimentBranchTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosExperimentBranch ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosExperimentBranch.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosExperimentBranch.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosExperimentBranch.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.cs new file mode 100644 index 00000000000..216c1384ab4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a branch in the step. 9 total per experiment. + public partial class ChaosExperimentBranch : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranchInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _action; + + /// List of actions. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Action { get => this._action; set => this._action = value; } + + /// Backing field for property. + private string _name; + + /// String of the branch name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public ChaosExperimentBranch() + { + + } + } + /// Model that represents a branch in the step. 9 total per experiment. + public partial interface IChaosExperimentBranch : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// List of actions. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of actions.", + SerializedName = @"actions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction) })] + System.Collections.Generic.List Action { get; set; } + /// String of the branch name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String of the branch name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Model that represents a branch in the step. 9 total per experiment. + internal partial interface IChaosExperimentBranchInternal + + { + /// List of actions. + System.Collections.Generic.List Action { get; set; } + /// String of the branch name. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.json.cs new file mode 100644 index 00000000000..1c41ff8a431 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentBranch.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a branch in the step. 9 total per experiment. + public partial class ChaosExperimentBranch + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosExperimentBranch(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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;} + {_action = If( json?.PropertyT("actions"), out var __jsonActions) ? If( __jsonActions as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IChaosExperimentAction) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction.FromJson(__u) )) ))() : null : _action;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosExperimentBranch(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + if (null != this._action) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._action ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("actions",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.PowerShell.cs new file mode 100644 index 00000000000..980ad72c386 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a step in the Experiment resource. + [System.ComponentModel.TypeConverter(typeof(ChaosExperimentStepTypeConverter))] + public partial class ChaosExperimentStep + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosExperimentStep(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.Chaos.Models.IChaosExperimentStepInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Branch")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal)this).Branch = (System.Collections.Generic.List) content.GetValueForProperty("Branch",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal)this).Branch, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentBranchTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ChaosExperimentStep(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.Chaos.Models.IChaosExperimentStepInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Branch")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal)this).Branch = (System.Collections.Generic.List) content.GetValueForProperty("Branch",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal)this).Branch, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentBranchTypeConverter.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.Chaos.Models.IChaosExperimentStep DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosExperimentStep(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosExperimentStep(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a step in the Experiment resource. + [System.ComponentModel.TypeConverter(typeof(ChaosExperimentStepTypeConverter))] + public partial interface IChaosExperimentStep + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.TypeConverter.cs new file mode 100644 index 00000000000..242ec979a3e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosExperimentStepTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosExperimentStep ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosExperimentStep.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosExperimentStep.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosExperimentStep.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.cs new file mode 100644 index 00000000000..1cbedc74376 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a step in the Experiment resource. + public partial class ChaosExperimentStep : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStepInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _branch; + + /// List of branches. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Branch { get => this._branch; set => this._branch = value; } + + /// Backing field for property. + private string _name; + + /// String of the step name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public ChaosExperimentStep() + { + + } + } + /// Model that represents a step in the Experiment resource. + public partial interface IChaosExperimentStep : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// List of branches. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of branches.", + SerializedName = @"branches", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentBranch) })] + System.Collections.Generic.List Branch { get; set; } + /// String of the step name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String of the step name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Model that represents a step in the Experiment resource. + internal partial interface IChaosExperimentStepInternal + + { + /// List of branches. + System.Collections.Generic.List Branch { get; set; } + /// String of the step name. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.json.cs new file mode 100644 index 00000000000..b448615ec43 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosExperimentStep.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a step in the Experiment resource. + public partial class ChaosExperimentStep + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosExperimentStep(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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;} + {_branch = If( json?.PropertyT("branches"), out var __jsonBranches) ? If( __jsonBranches as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IChaosExperimentBranch) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentBranch.FromJson(__u) )) ))() : null : _branch;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosExperimentStep(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + if (null != this._branch) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._branch ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("branches",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.PowerShell.cs new file mode 100644 index 00000000000..51433b0d166 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.PowerShell.cs @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ChaosIdentityTypeConverter))] + public partial class ChaosIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosIdentity(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.Chaos.Models.IChaosIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("ParentProviderNamespace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentProviderNamespace = (string) content.GetValueForProperty("ParentProviderNamespace",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentProviderNamespace, global::System.Convert.ToString); + } + if (content.Contains("ParentResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceType = (string) content.GetValueForProperty("ParentResourceType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceType, global::System.Convert.ToString); + } + if (content.Contains("ParentResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceName = (string) content.GetValueForProperty("ParentResourceName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceName, global::System.Convert.ToString); + } + if (content.Contains("TargetName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetName = (string) content.GetValueForProperty("TargetName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetName, global::System.Convert.ToString); + } + if (content.Contains("CapabilityName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityName = (string) content.GetValueForProperty("CapabilityName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityName, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("TargetTypeName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetTypeName = (string) content.GetValueForProperty("TargetTypeName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetTypeName, global::System.Convert.ToString); + } + if (content.Contains("CapabilityTypeName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityTypeName = (string) content.GetValueForProperty("CapabilityTypeName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityTypeName, global::System.Convert.ToString); + } + if (content.Contains("ExperimentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExperimentName = (string) content.GetValueForProperty("ExperimentName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExperimentName, global::System.Convert.ToString); + } + if (content.Contains("ExecutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExecutionId = (string) content.GetValueForProperty("ExecutionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExecutionId, global::System.Convert.ToString); + } + if (content.Contains("OperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).OperationId = (string) content.GetValueForProperty("OperationId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).OperationId, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)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 ChaosIdentity(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.Chaos.Models.IChaosIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("ParentProviderNamespace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentProviderNamespace = (string) content.GetValueForProperty("ParentProviderNamespace",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentProviderNamespace, global::System.Convert.ToString); + } + if (content.Contains("ParentResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceType = (string) content.GetValueForProperty("ParentResourceType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceType, global::System.Convert.ToString); + } + if (content.Contains("ParentResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceName = (string) content.GetValueForProperty("ParentResourceName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ParentResourceName, global::System.Convert.ToString); + } + if (content.Contains("TargetName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetName = (string) content.GetValueForProperty("TargetName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetName, global::System.Convert.ToString); + } + if (content.Contains("CapabilityName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityName = (string) content.GetValueForProperty("CapabilityName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityName, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("TargetTypeName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetTypeName = (string) content.GetValueForProperty("TargetTypeName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).TargetTypeName, global::System.Convert.ToString); + } + if (content.Contains("CapabilityTypeName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityTypeName = (string) content.GetValueForProperty("CapabilityTypeName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).CapabilityTypeName, global::System.Convert.ToString); + } + if (content.Contains("ExperimentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExperimentName = (string) content.GetValueForProperty("ExperimentName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExperimentName, global::System.Convert.ToString); + } + if (content.Contains("ExecutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExecutionId = (string) content.GetValueForProperty("ExecutionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).ExecutionId, global::System.Convert.ToString); + } + if (content.Contains("OperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).OperationId = (string) content.GetValueForProperty("OperationId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).OperationId, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal)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.Chaos.Models.IChaosIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosIdentity(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosIdentity(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(ChaosIdentityTypeConverter))] + public partial interface IChaosIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.TypeConverter.cs new file mode 100644 index 00000000000..c812cce24cd --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosIdentity 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 ChaosIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosIdentity.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.cs new file mode 100644 index 00000000000..bf1cc4472b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.cs @@ -0,0 +1,309 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + public partial class ChaosIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentityInternal + { + + /// Backing field for property. + private string _capabilityName; + + /// String that represents a Capability resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string CapabilityName { get => this._capabilityName; set => this._capabilityName = value; } + + /// Backing field for property. + private string _capabilityTypeName; + + /// String that represents a Capability Type resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string CapabilityTypeName { get => this._capabilityTypeName; set => this._capabilityTypeName = value; } + + /// Backing field for property. + private string _executionId; + + /// GUID that represents a Experiment execution detail. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ExecutionId { get => this._executionId; set => this._executionId = value; } + + /// Backing field for property. + private string _experimentName; + + /// String that represents a Experiment resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ExperimentName { get => this._experimentName; set => this._experimentName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _location; + + /// The name of the Azure region. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private string _operationId; + + /// The ID of an ongoing async operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string OperationId { get => this._operationId; set => this._operationId = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string TargetName { get => this._targetName; set => this._targetName = value; } + + /// Backing field for property. + private string _targetTypeName; + + /// String that represents a Target Type resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string TargetTypeName { get => this._targetTypeName; set => this._targetTypeName = value; } + + /// Creates an new instance. + public ChaosIdentity() + { + + } + } + public partial interface IChaosIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// String that represents a Capability resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + string CapabilityName { get; set; } + /// String that represents a Capability Type resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a Capability Type resource name.", + SerializedName = @"capabilityTypeName", + PossibleTypes = new [] { typeof(string) })] + string CapabilityTypeName { get; set; } + /// GUID that represents a Experiment execution detail. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"GUID that represents a Experiment execution detail.", + SerializedName = @"executionId", + PossibleTypes = new [] { typeof(string) })] + string ExecutionId { get; set; } + /// String that represents a Experiment resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + string ExperimentName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Azure region. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The ID of an ongoing async operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ID of an ongoing async operation.", + SerializedName = @"operationId", + PossibleTypes = new [] { typeof(string) })] + string OperationId { get; set; } + /// The parent resource provider namespace. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + string ParentProviderNamespace { get; set; } + /// The parent resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + string ParentResourceName { get; set; } + /// The parent resource type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + string ParentResourceType { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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; } + /// String that represents a Target resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + string TargetName { get; set; } + /// String that represents a Target Type resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a Target Type resource name.", + SerializedName = @"targetTypeName", + PossibleTypes = new [] { typeof(string) })] + string TargetTypeName { get; set; } + + } + internal partial interface IChaosIdentityInternal + + { + /// String that represents a Capability resource name. + string CapabilityName { get; set; } + /// String that represents a Capability Type resource name. + string CapabilityTypeName { get; set; } + /// GUID that represents a Experiment execution detail. + string ExecutionId { get; set; } + /// String that represents a Experiment resource name. + string ExperimentName { get; set; } + /// Resource identity path + string Id { get; set; } + /// The name of the Azure region. + string Location { get; set; } + /// The ID of an ongoing async operation. + string OperationId { get; set; } + /// The parent resource provider namespace. + string ParentProviderNamespace { get; set; } + /// The parent resource name. + string ParentResourceName { get; set; } + /// The parent resource type. + string ParentResourceType { 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; } + /// String that represents a Target resource name. + string TargetName { get; set; } + /// String that represents a Target Type resource name. + string TargetTypeName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.json.cs new file mode 100644 index 00000000000..eb0d17a9a77 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosIdentity.json.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + public partial class ChaosIdentity + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosIdentity(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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;} + {_parentProviderNamespace = If( json?.PropertyT("parentProviderNamespace"), out var __jsonParentProviderNamespace) ? (string)__jsonParentProviderNamespace : (string)_parentProviderNamespace;} + {_parentResourceType = If( json?.PropertyT("parentResourceType"), out var __jsonParentResourceType) ? (string)__jsonParentResourceType : (string)_parentResourceType;} + {_parentResourceName = If( json?.PropertyT("parentResourceName"), out var __jsonParentResourceName) ? (string)__jsonParentResourceName : (string)_parentResourceName;} + {_targetName = If( json?.PropertyT("targetName"), out var __jsonTargetName) ? (string)__jsonTargetName : (string)_targetName;} + {_capabilityName = If( json?.PropertyT("capabilityName"), out var __jsonCapabilityName) ? (string)__jsonCapabilityName : (string)_capabilityName;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + {_targetTypeName = If( json?.PropertyT("targetTypeName"), out var __jsonTargetTypeName) ? (string)__jsonTargetTypeName : (string)_targetTypeName;} + {_capabilityTypeName = If( json?.PropertyT("capabilityTypeName"), out var __jsonCapabilityTypeName) ? (string)__jsonCapabilityTypeName : (string)_capabilityTypeName;} + {_experimentName = If( json?.PropertyT("experimentName"), out var __jsonExperimentName) ? (string)__jsonExperimentName : (string)_experimentName;} + {_executionId = If( json?.PropertyT("executionId"), out var __jsonExecutionId) ? (string)__jsonExecutionId : (string)_executionId;} + {_operationId = If( json?.PropertyT("operationId"), out var __jsonOperationId) ? (string)__jsonOperationId : (string)_operationId;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosIdentity(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._parentProviderNamespace)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._parentProviderNamespace.ToString()) : null, "parentProviderNamespace" ,container.Add ); + AddIf( null != (((object)this._parentResourceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._parentResourceType.ToString()) : null, "parentResourceType" ,container.Add ); + AddIf( null != (((object)this._parentResourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._parentResourceName.ToString()) : null, "parentResourceName" ,container.Add ); + AddIf( null != (((object)this._targetName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._targetName.ToString()) : null, "targetName" ,container.Add ); + AddIf( null != (((object)this._capabilityName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._capabilityName.ToString()) : null, "capabilityName" ,container.Add ); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != (((object)this._targetTypeName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._targetTypeName.ToString()) : null, "targetTypeName" ,container.Add ); + AddIf( null != (((object)this._capabilityTypeName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._capabilityTypeName.ToString()) : null, "capabilityTypeName" ,container.Add ); + AddIf( null != (((object)this._experimentName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._experimentName.ToString()) : null, "experimentName" ,container.Add ); + AddIf( null != (((object)this._executionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._executionId.ToString()) : null, "executionId" ,container.Add ); + AddIf( null != (((object)this._operationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._operationId.ToString()) : null, "operationId" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.PowerShell.cs new file mode 100644 index 00000000000..c86871119b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + [System.ComponentModel.TypeConverter(typeof(ChaosTargetFilterTypeConverter))] + public partial class ChaosTargetFilter + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosTargetFilter(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.Chaos.Models.IChaosTargetFilterInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)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 ChaosTargetFilter(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.Chaos.Models.IChaosTargetFilterInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosTargetFilter(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosTargetFilter(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents available filter types that can be applied to a targets list. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetFilterTypeConverter))] + public partial interface IChaosTargetFilter + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.TypeConverter.cs new file mode 100644 index 00000000000..70ad4692d1e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosTargetFilterTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosTargetFilter ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosTargetFilter.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosTargetFilter.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosTargetFilter.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.cs new file mode 100644 index 00000000000..2df2d328ec5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + public partial class ChaosTargetFilter : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal + { + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type= @"Simple"; + + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ChaosTargetFilter() + { + + } + } + /// Model that represents available filter types that can be applied to a targets list. + public partial interface IChaosTargetFilter : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = true, + Read = true, + Create = true, + Update = true, + Description = @"Chaos target filter discriminator type", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Model that represents available filter types that can be applied to a targets list. + internal partial interface IChaosTargetFilterInternal + + { + /// Chaos target filter discriminator type + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.json.cs new file mode 100644 index 00000000000..db0dbb0aa78 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetFilter.json.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + public partial class ChaosTargetFilter + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosTargetFilter(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter interface is polymorphic, and the precise + /// model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("type") ) + { + case "Simple": + { + return new ChaosTargetSimpleFilter(json); + } + } + return new ChaosTargetFilter(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.PowerShell.cs new file mode 100644 index 00000000000..eafcafb4fc1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a list selector. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetListSelectorTypeConverter))] + public partial class ChaosTargetListSelector + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosTargetListSelector(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelectorInternal)this).Target = (System.Collections.Generic.List) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelectorInternal)this).Target, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetReferenceTypeConverter.ConvertFrom)); + } + if (content.Contains("FilterType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType = (string) content.GetValueForProperty("FilterType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType, global::System.Convert.ToString); + } + if (content.Contains("Filter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter) content.GetValueForProperty("Filter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilterTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)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 ChaosTargetListSelector(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelectorInternal)this).Target = (System.Collections.Generic.List) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelectorInternal)this).Target, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetReferenceTypeConverter.ConvertFrom)); + } + if (content.Contains("FilterType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType = (string) content.GetValueForProperty("FilterType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType, global::System.Convert.ToString); + } + if (content.Contains("Filter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter) content.GetValueForProperty("Filter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilterTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosTargetListSelector(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosTargetListSelector(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a list selector. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetListSelectorTypeConverter))] + public partial interface IChaosTargetListSelector + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.TypeConverter.cs new file mode 100644 index 00000000000..c33344e9884 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosTargetListSelectorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosTargetListSelector ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosTargetListSelector.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosTargetListSelector.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosTargetListSelector.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.cs new file mode 100644 index 00000000000..c16e8b5fe7c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list selector. + public partial class ChaosTargetListSelector : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelectorInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector __chaosTargetSelector = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelector(); + + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Filter { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter = value ?? null /* model class */; } + + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string FilterType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).FilterType; } + + /// String of the selector ID. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Id = value ; } + + /// Internal Acessors for Filter + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal.Filter { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter = value ?? null /* model class */; } + + /// Internal Acessors for FilterType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal.FilterType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).FilterType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).FilterType = value ?? null; } + + /// Backing field for property. + private System.Collections.Generic.List _target; + + /// List of Target references. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Target { get => this._target; set => this._target = value; } + + /// Chaos target selector discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => "List"; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Type = "List"; } + + /// Creates an new instance. + public ChaosTargetListSelector() + { + this.__chaosTargetSelector.Type = "List"; + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__chaosTargetSelector), __chaosTargetSelector); + await eventListener.AssertObjectIsValid(nameof(__chaosTargetSelector), __chaosTargetSelector); + } + } + /// Model that represents a list selector. + public partial interface IChaosTargetListSelector : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector + { + /// List of Target references. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of Target references.", + SerializedName = @"targets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference) })] + System.Collections.Generic.List Target { get; set; } + + } + /// Model that represents a list selector. + internal partial interface IChaosTargetListSelectorInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal + { + /// List of Target references. + System.Collections.Generic.List Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.json.cs new file mode 100644 index 00000000000..71edfd33c03 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetListSelector.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list selector. + public partial class ChaosTargetListSelector + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosTargetListSelector(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __chaosTargetSelector = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelector(json); + {_target = If( json?.PropertyT("targets"), out var __jsonTargets) ? If( __jsonTargets as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITargetReference) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetReference.FromJson(__u) )) ))() : null : _target;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosTargetListSelector(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __chaosTargetSelector?.ToJson(container, serializationMode); + if (null != this._target) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._target ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("targets",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.PowerShell.cs new file mode 100644 index 00000000000..c079a690cda --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a query selector. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetQuerySelectorTypeConverter))] + public partial class ChaosTargetQuerySelector + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosTargetQuerySelector(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("QueryString")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).QueryString = (string) content.GetValueForProperty("QueryString",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).QueryString, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).SubscriptionId = (System.Collections.Generic.List) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).SubscriptionId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("FilterType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType = (string) content.GetValueForProperty("FilterType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType, global::System.Convert.ToString); + } + if (content.Contains("Filter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter) content.GetValueForProperty("Filter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilterTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)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 ChaosTargetQuerySelector(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("QueryString")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).QueryString = (string) content.GetValueForProperty("QueryString",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).QueryString, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).SubscriptionId = (System.Collections.Generic.List) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal)this).SubscriptionId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("FilterType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType = (string) content.GetValueForProperty("FilterType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType, global::System.Convert.ToString); + } + if (content.Contains("Filter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter) content.GetValueForProperty("Filter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilterTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosTargetQuerySelector(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosTargetQuerySelector(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a query selector. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetQuerySelectorTypeConverter))] + public partial interface IChaosTargetQuerySelector + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.TypeConverter.cs new file mode 100644 index 00000000000..2bef7e487db --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosTargetQuerySelectorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosTargetQuerySelector ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosTargetQuerySelector.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosTargetQuerySelector.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosTargetQuerySelector.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.cs new file mode 100644 index 00000000000..49f3b5a3cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a query selector. + public partial class ChaosTargetQuerySelector : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelectorInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector __chaosTargetSelector = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelector(); + + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Filter { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter = value ?? null /* model class */; } + + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string FilterType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).FilterType; } + + /// String of the selector ID. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Id = value ; } + + /// Internal Acessors for Filter + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal.Filter { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Filter = value ?? null /* model class */; } + + /// Internal Acessors for FilterType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal.FilterType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).FilterType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).FilterType = value ?? null; } + + /// Backing field for property. + private string _queryString; + + /// Azure Resource Graph (ARG) Query Language query for target resources. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string QueryString { get => this._queryString; set => this._queryString = value; } + + /// Backing field for property. + private System.Collections.Generic.List _subscriptionId; + + /// Subscription id list to scope resource query. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Chaos target selector discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => "Query"; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)__chaosTargetSelector).Type = "Query"; } + + /// Creates an new instance. + public ChaosTargetQuerySelector() + { + this.__chaosTargetSelector.Type = "Query"; + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__chaosTargetSelector), __chaosTargetSelector); + await eventListener.AssertObjectIsValid(nameof(__chaosTargetSelector), __chaosTargetSelector); + } + } + /// Model that represents a query selector. + public partial interface IChaosTargetQuerySelector : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector + { + /// Azure Resource Graph (ARG) Query Language query for target resources. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure Resource Graph (ARG) Query Language query for target resources.", + SerializedName = @"queryString", + PossibleTypes = new [] { typeof(string) })] + string QueryString { get; set; } + /// Subscription id list to scope resource query. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription id list to scope resource query.", + SerializedName = @"subscriptionIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SubscriptionId { get; set; } + + } + /// Model that represents a query selector. + internal partial interface IChaosTargetQuerySelectorInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal + { + /// Azure Resource Graph (ARG) Query Language query for target resources. + string QueryString { get; set; } + /// Subscription id list to scope resource query. + System.Collections.Generic.List SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.json.cs new file mode 100644 index 00000000000..61bd3aa9b37 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetQuerySelector.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a query selector. + public partial class ChaosTargetQuerySelector + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosTargetQuerySelector(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __chaosTargetSelector = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelector(json); + {_queryString = If( json?.PropertyT("queryString"), out var __jsonQueryString) ? (string)__jsonQueryString : (string)_queryString;} + {_subscriptionId = If( json?.PropertyT("subscriptionIds"), out var __jsonSubscriptionIds) ? If( __jsonSubscriptionIds as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _subscriptionId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosTargetQuerySelector(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __chaosTargetSelector?.ToJson(container, serializationMode); + AddIf( null != (((object)this._queryString)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._queryString.ToString()) : null, "queryString" ,container.Add ); + if (null != this._subscriptionId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._subscriptionId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("subscriptionIds",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.PowerShell.cs new file mode 100644 index 00000000000..6884c064e74 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a selector in the Experiment resource. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetSelectorTypeConverter))] + public partial class ChaosTargetSelector + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosTargetSelector(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Filter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter) content.GetValueForProperty("Filter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilterTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("FilterType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType = (string) content.GetValueForProperty("FilterType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType, 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 ChaosTargetSelector(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Filter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter) content.GetValueForProperty("Filter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Filter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilterTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("FilterType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType = (string) content.GetValueForProperty("FilterType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal)this).FilterType, 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.Chaos.Models.IChaosTargetSelector DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosTargetSelector(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosTargetSelector(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a selector in the Experiment resource. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetSelectorTypeConverter))] + public partial interface IChaosTargetSelector + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.TypeConverter.cs new file mode 100644 index 00000000000..8eae71da2a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosTargetSelectorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosTargetSelector ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosTargetSelector.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosTargetSelector.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosTargetSelector.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.cs new file mode 100644 index 00000000000..04b2bd85a49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a selector in the Experiment resource. + public partial class ChaosTargetSelector : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter _filter; + + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Filter { get => (this._filter = this._filter ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilter()); set => this._filter = value; } + + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string FilterType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)Filter).Type; } + + /// Backing field for property. + private string _id; + + /// String of the selector ID. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Internal Acessors for Filter + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal.Filter { get => (this._filter = this._filter ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilter()); set { {_filter = value;} } } + + /// Internal Acessors for FilterType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelectorInternal.FilterType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)Filter).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)Filter).Type = value ?? null; } + + /// Backing field for property. + private string _type; + + /// Chaos target selector discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public ChaosTargetSelector() + { + + } + } + /// Model that represents a selector in the Experiment resource. + public partial interface IChaosTargetSelector : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = true, + Update = true, + Description = @"Chaos target filter discriminator type", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string FilterType { get; } + /// String of the selector ID. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String of the selector ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Chaos target selector discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Chaos target selector discriminator type", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("List", "Query")] + string Type { get; set; } + + } + /// Model that represents a selector in the Experiment resource. + internal partial interface IChaosTargetSelectorInternal + + { + /// + /// Model that represents available filter types that can be applied to a targets list. + /// + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter Filter { get; set; } + /// Chaos target filter discriminator type + string FilterType { get; set; } + /// String of the selector ID. + string Id { get; set; } + /// Chaos target selector discriminator type + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("List", "Query")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.json.cs new file mode 100644 index 00000000000..d01377a4e5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSelector.json.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a selector in the Experiment resource. + public partial class ChaosTargetSelector + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosTargetSelector(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_filter = If( json?.PropertyT("filter"), out var __jsonFilter) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilter.FromJson(__jsonFilter) : _filter;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector interface is polymorphic, and the precise + /// model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("type") ) + { + case "List": + { + return new ChaosTargetListSelector(json); + } + case "Query": + { + return new ChaosTargetQuerySelector(json); + } + } + return new ChaosTargetSelector(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._filter ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._filter.ToJson(null,serializationMode) : null, "filter" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.PowerShell.cs new file mode 100644 index 00000000000..35e4ccfcf84 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a simple target filter. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetSimpleFilterTypeConverter))] + public partial class ChaosTargetSimpleFilter + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosTargetSimpleFilter(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Parameter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).Parameter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).Parameter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSimpleFilterParametersTypeConverter.ConvertFrom); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ParameterZone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).ParameterZone = (System.Collections.Generic.List) content.GetValueForProperty("ParameterZone",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).ParameterZone, __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 ChaosTargetSimpleFilter(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Parameter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).Parameter = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).Parameter, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSimpleFilterParametersTypeConverter.ConvertFrom); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ParameterZone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).ParameterZone = (System.Collections.Generic.List) content.GetValueForProperty("ParameterZone",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal)this).ParameterZone, __y => TypeConverterExtensions.SelectToList(__y, 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.Chaos.Models.IChaosTargetSimpleFilter DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosTargetSimpleFilter(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosTargetSimpleFilter(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a simple target filter. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetSimpleFilterTypeConverter))] + public partial interface IChaosTargetSimpleFilter + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.TypeConverter.cs new file mode 100644 index 00000000000..c8e836dd3fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosTargetSimpleFilterTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosTargetSimpleFilter ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosTargetSimpleFilter.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosTargetSimpleFilter.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosTargetSimpleFilter.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.cs new file mode 100644 index 00000000000..6b4892f40f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a simple target filter. + public partial class ChaosTargetSimpleFilter : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter __chaosTargetFilter = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilter(); + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)__chaosTargetFilter).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal)__chaosTargetFilter).Type = value ; } + + /// Internal Acessors for Parameter + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterInternal.Parameter { get => (this._parameter = this._parameter ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSimpleFilterParameters()); set { {_parameter = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters _parameter; + + /// Model that represents the Simple filter parameters. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters Parameter { get => (this._parameter = this._parameter ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSimpleFilterParameters()); set => this._parameter = value; } + + /// List of Azure availability zones to filter targets by. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List ParameterZone { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal)Parameter).Zone; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal)Parameter).Zone = value ?? null /* arrayOf */; } + + /// Chaos target filter discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => "Simple"; } + + /// Creates an new instance. + public ChaosTargetSimpleFilter() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__chaosTargetFilter), __chaosTargetFilter); + await eventListener.AssertObjectIsValid(nameof(__chaosTargetFilter), __chaosTargetFilter); + } + } + /// Model that represents a simple target filter. + public partial interface IChaosTargetSimpleFilter : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilter + { + /// List of Azure availability zones to filter targets by. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of Azure availability zones to filter targets by.", + SerializedName = @"zones", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List ParameterZone { get; set; } + + } + /// Model that represents a simple target filter. + internal partial interface IChaosTargetSimpleFilterInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetFilterInternal + { + /// Model that represents the Simple filter parameters. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters Parameter { get; set; } + /// List of Azure availability zones to filter targets by. + System.Collections.Generic.List ParameterZone { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.json.cs new file mode 100644 index 00000000000..fc091b442f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilter.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a simple target filter. + public partial class ChaosTargetSimpleFilter + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosTargetSimpleFilter(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __chaosTargetFilter = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetFilter(json); + {_parameter = If( json?.PropertyT("parameters"), out var __jsonParameters) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSimpleFilterParameters.FromJson(__jsonParameters) : _parameter;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilter FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosTargetSimpleFilter(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __chaosTargetFilter?.ToJson(container, serializationMode); + AddIf( null != this._parameter ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._parameter.ToJson(null,serializationMode) : null, "parameters" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.PowerShell.cs new file mode 100644 index 00000000000..346e2d10c4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the Simple filter parameters. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetSimpleFilterParametersTypeConverter))] + public partial class ChaosTargetSimpleFilterParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ChaosTargetSimpleFilterParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Zone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal)this).Zone = (System.Collections.Generic.List) content.GetValueForProperty("Zone",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal)this).Zone, __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 ChaosTargetSimpleFilterParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Zone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal)this).Zone = (System.Collections.Generic.List) content.GetValueForProperty("Zone",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal)this).Zone, __y => TypeConverterExtensions.SelectToList(__y, 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.Chaos.Models.IChaosTargetSimpleFilterParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ChaosTargetSimpleFilterParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ChaosTargetSimpleFilterParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the Simple filter parameters. + [System.ComponentModel.TypeConverter(typeof(ChaosTargetSimpleFilterParametersTypeConverter))] + public partial interface IChaosTargetSimpleFilterParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.TypeConverter.cs new file mode 100644 index 00000000000..9dea3d13e57 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ChaosTargetSimpleFilterParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IChaosTargetSimpleFilterParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ChaosTargetSimpleFilterParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ChaosTargetSimpleFilterParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ChaosTargetSimpleFilterParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.cs new file mode 100644 index 00000000000..dac01dd4aaf --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Simple filter parameters. + public partial class ChaosTargetSimpleFilterParameters : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParametersInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _zone; + + /// List of Azure availability zones to filter targets by. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Zone { get => this._zone; set => this._zone = value; } + + /// Creates an new instance. + public ChaosTargetSimpleFilterParameters() + { + + } + } + /// Model that represents the Simple filter parameters. + public partial interface IChaosTargetSimpleFilterParameters : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// List of Azure availability zones to filter targets by. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of Azure availability zones to filter targets by.", + SerializedName = @"zones", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List Zone { get; set; } + + } + /// Model that represents the Simple filter parameters. + internal partial interface IChaosTargetSimpleFilterParametersInternal + + { + /// List of Azure availability zones to filter targets by. + System.Collections.Generic.List Zone { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.json.cs new file mode 100644 index 00000000000..dd8adcbdb32 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ChaosTargetSimpleFilterParameters.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Simple filter parameters. + public partial class ChaosTargetSimpleFilterParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ChaosTargetSimpleFilterParameters(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_zone = If( json?.PropertyT("zones"), out var __jsonZones) ? If( __jsonZones as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _zone;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSimpleFilterParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ChaosTargetSimpleFilterParameters(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._zone) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._zone ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("zones",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.PowerShell.cs new file mode 100644 index 00000000000..517979e8719 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a continuous action. + [System.ComponentModel.TypeConverter(typeof(ContinuousActionTypeConverter))] + public partial class ContinuousAction + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ContinuousAction(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Duration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Duration = (global::System.TimeSpan) content.GetValueForProperty("Duration",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Duration, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); + } + if (content.Contains("Parameter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Parameter = (System.Collections.Generic.List) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Parameter, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.KeyValuePairTypeConverter.ConvertFrom)); + } + if (content.Contains("SelectorId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).SelectorId = (string) content.GetValueForProperty("SelectorId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).SelectorId, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)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 ContinuousAction(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Duration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Duration = (global::System.TimeSpan) content.GetValueForProperty("Duration",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Duration, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); + } + if (content.Contains("Parameter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Parameter = (System.Collections.Generic.List) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).Parameter, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.KeyValuePairTypeConverter.ConvertFrom)); + } + if (content.Contains("SelectorId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).SelectorId = (string) content.GetValueForProperty("SelectorId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal)this).SelectorId, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ContinuousAction(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ContinuousAction(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a continuous action. + [System.ComponentModel.TypeConverter(typeof(ContinuousActionTypeConverter))] + public partial interface IContinuousAction + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.TypeConverter.cs new file mode 100644 index 00000000000..65803c39346 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ContinuousActionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IContinuousAction ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ContinuousAction.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ContinuousAction.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ContinuousAction.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.cs new file mode 100644 index 00000000000..cb6e9ba228e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a continuous action. + public partial class ContinuousAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousActionInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction __chaosExperimentAction = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction(); + + /// Backing field for property. + private global::System.TimeSpan _duration; + + /// ISO8601 formatted string that represents a duration. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.TimeSpan Duration { get => this._duration; set => this._duration = value; } + + /// String that represents a Capability URN. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Name = value ; } + + /// Backing field for property. + private System.Collections.Generic.List _parameter; + + /// List of key value pairs. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Parameter { get => this._parameter; set => this._parameter = value; } + + /// Backing field for property. + private string _selectorId; + + /// String that represents a selector. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string SelectorId { get => this._selectorId; set => this._selectorId = value; } + + /// Chaos experiment action discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => "continuous"; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Type = "continuous"; } + + /// Creates an new instance. + public ContinuousAction() + { + this.__chaosExperimentAction.Type = "continuous"; + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__chaosExperimentAction), __chaosExperimentAction); + await eventListener.AssertObjectIsValid(nameof(__chaosExperimentAction), __chaosExperimentAction); + } + } + /// Model that represents a continuous action. + public partial interface IContinuousAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction + { + /// ISO8601 formatted string that represents a duration. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"ISO8601 formatted string that represents a duration.", + SerializedName = @"duration", + PossibleTypes = new [] { typeof(global::System.TimeSpan) })] + global::System.TimeSpan Duration { get; set; } + /// List of key value pairs. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of key value pairs.", + SerializedName = @"parameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair) })] + System.Collections.Generic.List Parameter { get; set; } + /// String that represents a selector. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a selector.", + SerializedName = @"selectorId", + PossibleTypes = new [] { typeof(string) })] + string SelectorId { get; set; } + + } + /// Model that represents a continuous action. + internal partial interface IContinuousActionInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal + { + /// ISO8601 formatted string that represents a duration. + global::System.TimeSpan Duration { get; set; } + /// List of key value pairs. + System.Collections.Generic.List Parameter { get; set; } + /// String that represents a selector. + string SelectorId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.json.cs new file mode 100644 index 00000000000..9d1a48e21cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ContinuousAction.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a continuous action. + public partial class ContinuousAction + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ContinuousAction(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __chaosExperimentAction = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction(json); + {_duration = If( json?.PropertyT("duration"), out var __jsonDuration) ? global::System.Xml.XmlConvert.ToTimeSpan( __jsonDuration ) : _duration;} + {_parameter = If( json?.PropertyT("parameters"), out var __jsonParameters) ? If( __jsonParameters as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IKeyValuePair) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.KeyValuePair.FromJson(__u) )) ))() : null : _parameter;} + {_selectorId = If( json?.PropertyT("selectorId"), out var __jsonSelectorId) ? (string)__jsonSelectorId : (string)_selectorId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IContinuousAction FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ContinuousAction(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __chaosExperimentAction?.ToJson(container, serializationMode); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(global::System.Xml.XmlConvert.ToString((global::System.TimeSpan)this._duration)), "duration" ,container.Add ); + if (null != this._parameter) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._parameter ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("parameters",__w); + } + AddIf( null != (((object)this._selectorId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._selectorId.ToString()) : null, "selectorId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.PowerShell.cs new file mode 100644 index 00000000000..cb6534cc30a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a delay action. + [System.ComponentModel.TypeConverter(typeof(DelayActionTypeConverter))] + public partial class DelayAction + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 DelayAction(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Duration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayActionInternal)this).Duration = (global::System.TimeSpan) content.GetValueForProperty("Duration",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayActionInternal)this).Duration, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)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 DelayAction(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Duration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayActionInternal)this).Duration = (global::System.TimeSpan) content.GetValueForProperty("Duration",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayActionInternal)this).Duration, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DelayAction(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DelayAction(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a delay action. + [System.ComponentModel.TypeConverter(typeof(DelayActionTypeConverter))] + public partial interface IDelayAction + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.TypeConverter.cs new file mode 100644 index 00000000000..5b350af4ada --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DelayActionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IDelayAction ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DelayAction.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DelayAction.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DelayAction.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/DelayAction.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.cs new file mode 100644 index 00000000000..c920598315c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a delay action. + public partial class DelayAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayActionInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction __chaosExperimentAction = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction(); + + /// Backing field for property. + private global::System.TimeSpan _duration; + + /// ISO8601 formatted string that represents a duration. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.TimeSpan Duration { get => this._duration; set => this._duration = value; } + + /// String that represents a Capability URN. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Name = value ; } + + /// Chaos experiment action discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => "delay"; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Type = "delay"; } + + /// Creates an new instance. + public DelayAction() + { + this.__chaosExperimentAction.Type = "delay"; + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__chaosExperimentAction), __chaosExperimentAction); + await eventListener.AssertObjectIsValid(nameof(__chaosExperimentAction), __chaosExperimentAction); + } + } + /// Model that represents a delay action. + public partial interface IDelayAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction + { + /// ISO8601 formatted string that represents a duration. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"ISO8601 formatted string that represents a duration.", + SerializedName = @"duration", + PossibleTypes = new [] { typeof(global::System.TimeSpan) })] + global::System.TimeSpan Duration { get; set; } + + } + /// Model that represents a delay action. + internal partial interface IDelayActionInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal + { + /// ISO8601 formatted string that represents a duration. + global::System.TimeSpan Duration { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.json.cs new file mode 100644 index 00000000000..4d8140f1b90 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DelayAction.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a delay action. + public partial class DelayAction + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal DelayAction(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __chaosExperimentAction = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction(json); + {_duration = If( json?.PropertyT("duration"), out var __jsonDuration) ? global::System.Xml.XmlConvert.ToTimeSpan( __jsonDuration ) : _duration;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDelayAction FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new DelayAction(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __chaosExperimentAction?.ToJson(container, serializationMode); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(global::System.Xml.XmlConvert.ToString((global::System.TimeSpan)this._duration)), "duration" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.PowerShell.cs new file mode 100644 index 00000000000..975f089bfef --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a discrete action. + [System.ComponentModel.TypeConverter(typeof(DiscreteActionTypeConverter))] + public partial class DiscreteAction + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IDiscreteAction DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DiscreteAction(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteAction DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DiscreteAction(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DiscreteAction(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Parameter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).Parameter = (System.Collections.Generic.List) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).Parameter, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.KeyValuePairTypeConverter.ConvertFrom)); + } + if (content.Contains("SelectorId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).SelectorId = (string) content.GetValueForProperty("SelectorId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).SelectorId, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)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 DiscreteAction(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Parameter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).Parameter = (System.Collections.Generic.List) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).Parameter, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.KeyValuePairTypeConverter.ConvertFrom)); + } + if (content.Contains("SelectorId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).SelectorId = (string) content.GetValueForProperty("SelectorId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal)this).SelectorId, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)this).Type, 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.Chaos.Models.IDiscreteAction FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a discrete action. + [System.ComponentModel.TypeConverter(typeof(DiscreteActionTypeConverter))] + public partial interface IDiscreteAction + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.TypeConverter.cs new file mode 100644 index 00000000000..9b1aa1777be --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DiscreteActionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IDiscreteAction ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteAction).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DiscreteAction.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DiscreteAction.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DiscreteAction.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.cs new file mode 100644 index 00000000000..90fa07c9fb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a discrete action. + public partial class DiscreteAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteAction, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteActionInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction __chaosExperimentAction = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction(); + + /// String that represents a Capability URN. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Name = value ; } + + /// Backing field for property. + private System.Collections.Generic.List _parameter; + + /// List of key value pairs. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Parameter { get => this._parameter; set => this._parameter = value; } + + /// Backing field for property. + private string _selectorId; + + /// String that represents a selector. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string SelectorId { get => this._selectorId; set => this._selectorId = value; } + + /// Chaos experiment action discriminator type + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => "discrete"; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal)__chaosExperimentAction).Type = "discrete"; } + + /// Creates an new instance. + public DiscreteAction() + { + this.__chaosExperimentAction.Type = "discrete"; + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__chaosExperimentAction), __chaosExperimentAction); + await eventListener.AssertObjectIsValid(nameof(__chaosExperimentAction), __chaosExperimentAction); + } + } + /// Model that represents a discrete action. + public partial interface IDiscreteAction : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentAction + { + /// List of key value pairs. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of key value pairs.", + SerializedName = @"parameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair) })] + System.Collections.Generic.List Parameter { get; set; } + /// String that represents a selector. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String that represents a selector.", + SerializedName = @"selectorId", + PossibleTypes = new [] { typeof(string) })] + string SelectorId { get; set; } + + } + /// Model that represents a discrete action. + internal partial interface IDiscreteActionInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentActionInternal + { + /// List of key value pairs. + System.Collections.Generic.List Parameter { get; set; } + /// String that represents a selector. + string SelectorId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.json.cs new file mode 100644 index 00000000000..647a2785f40 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/DiscreteAction.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a discrete action. + public partial class DiscreteAction + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal DiscreteAction(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __chaosExperimentAction = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentAction(json); + {_parameter = If( json?.PropertyT("parameters"), out var __jsonParameters) ? If( __jsonParameters as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IKeyValuePair) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.KeyValuePair.FromJson(__u) )) ))() : null : _parameter;} + {_selectorId = If( json?.PropertyT("selectorId"), out var __jsonSelectorId) ? (string)__jsonSelectorId : (string)_selectorId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteAction. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteAction. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IDiscreteAction FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new DiscreteAction(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __chaosExperimentAction?.ToJson(container, serializationMode); + if (null != this._parameter) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._parameter ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("parameters",__w); + } + AddIf( null != (((object)this._selectorId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._selectorId.ToString()) : null, "selectorId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..18ed7cd07cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..e47a2d94f15 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..91097c19d38 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..7553451b8df --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..91c6268e85e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..fa09beb0b85 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..36dc643aaed --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..a93e4543c70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..71f3d412f68 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..828ef719122 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..bc970aee513 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Message = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Target = value ?? null; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..7f9786ccac0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponse. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponse. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Experiment.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.PowerShell.cs new file mode 100644 index 00000000000..aeb1f0bb635 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.PowerShell.cs @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a Experiment resource. + [System.ComponentModel.TypeConverter(typeof(ExperimentTypeConverter))] + public partial class Experiment + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperiment DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Experiment(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Experiment(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Experiment(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.Chaos.Models.IExperimentInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("Step")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Step = (System.Collections.Generic.List) content.GetValueForProperty("Step",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Step, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentStepTypeConverter.ConvertFrom)); + } + if (content.Contains("Selector")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Selector = (System.Collections.Generic.List) content.GetValueForProperty("Selector",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Selector, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelectorTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Experiment(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.Chaos.Models.IExperimentInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("Step")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Step = (System.Collections.Generic.List) content.GetValueForProperty("Step",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Step, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentStepTypeConverter.ConvertFrom)); + } + if (content.Contains("Selector")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Selector = (System.Collections.Generic.List) content.GetValueForProperty("Selector",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal)this).Selector, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelectorTypeConverter.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.Chaos.Models.IExperiment FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a Experiment resource. + [System.ComponentModel.TypeConverter(typeof(ExperimentTypeConverter))] + public partial interface IExperiment + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.TypeConverter.cs new file mode 100644 index 00000000000..ed9b618a154 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperiment ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Experiment.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Experiment.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Experiment.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/Experiment.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.cs new file mode 100644 index 00000000000..5b1dcd1a719 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Experiment resource. + public partial class Experiment : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties _property; + + /// The properties of the experiment resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentProperties()); set => this._property = value; } + + /// Most recent provisioning state for the given experiment resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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); } + + /// List of selectors. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Selector { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).Selector; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).Selector = value ; } + + /// List of steps. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Step { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).Step; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)Property).Step = value ; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public Experiment() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Model that represents a Experiment resource. + public partial interface IExperiment : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Most recent provisioning state for the given experiment resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Most recent provisioning state for the given experiment resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; } + /// List of selectors. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of selectors.", + SerializedName = @"selectors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector) })] + System.Collections.Generic.List Selector { get; set; } + /// List of steps. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of steps.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep) })] + System.Collections.Generic.List Step { get; set; } + + } + /// Model that represents a Experiment resource. + internal partial interface IExperimentInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal + { + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// The properties of the experiment resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties Property { get; set; } + /// Most recent provisioning state for the given experiment resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; set; } + /// List of selectors. + System.Collections.Generic.List Selector { get; set; } + /// List of steps. + System.Collections.Generic.List Step { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.json.cs new file mode 100644 index 00000000000..26354a93889 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Experiment.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Experiment resource. + public partial class Experiment + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal Experiment(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResource(json); + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new Experiment(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __trackedResource?.ToJson(container, serializationMode); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.PowerShell.cs new file mode 100644 index 00000000000..730875f454a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.PowerShell.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the execution of a Experiment. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionTypeConverter))] + public partial class ExperimentExecution + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecution DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecution(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecution(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecution(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.Chaos.Models.IExperimentExecutionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StoppedAt, (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 ExperimentExecution(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.Chaos.Models.IExperimentExecutionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal)this).StoppedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + 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.Chaos.Models.IExperimentExecution FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the execution of a Experiment. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionTypeConverter))] + public partial interface IExperimentExecution + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.TypeConverter.cs new file mode 100644 index 00000000000..3d4de614c9e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecution ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecution.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecution.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecution.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.cs new file mode 100644 index 00000000000..73c84078bd6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the execution of a Experiment. + public partial class ExperimentExecution : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionProperties()); set { {_property = value;} } } + + /// Internal Acessors for StartedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal.StartedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).StartedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).StartedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).Status = value ?? null; } + + /// Internal Acessors for StoppedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionInternal.StoppedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).StoppedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).StoppedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties _property; + + /// The properties of experiment execution status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionProperties()); set => this._property = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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); } + + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? StartedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).StartedAt; } + + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).Status; } + + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? StoppedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)Property).StoppedAt; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public ExperimentExecution() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Model that represents the execution of a Experiment. + public partial interface IExperimentExecution : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource + { + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the start date time.", + SerializedName = @"startedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartedAt { get; } + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the execution.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the stop date time.", + SerializedName = @"stoppedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StoppedAt { get; } + + } + /// Model that represents the execution of a Experiment. + internal partial interface IExperimentExecutionInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResourceInternal + { + /// The properties of experiment execution status. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties Property { get; set; } + /// String that represents the start date time. + global::System.DateTime? StartedAt { get; set; } + /// The status of the execution. + string Status { get; set; } + /// String that represents the stop date time. + global::System.DateTime? StoppedAt { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.json.cs new file mode 100644 index 00000000000..2a3aaf4e985 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecution.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the execution of a Experiment. + public partial class ExperimentExecution + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecution(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecution(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.PowerShell.cs new file mode 100644 index 00000000000..2d61d367819 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the Experiment action target details error model. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionActionTargetDetailsErrorTypeConverter))] + public partial class ExperimentExecutionActionTargetDetailsError + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionActionTargetDetailsError DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionActionTargetDetailsError(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionActionTargetDetailsError(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionActionTargetDetailsError(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.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)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 ExperimentExecutionActionTargetDetailsError(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.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)this).Message, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a + /// json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the Experiment action target details error model. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionActionTargetDetailsErrorTypeConverter))] + public partial interface IExperimentExecutionActionTargetDetailsError + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.TypeConverter.cs new file mode 100644 index 00000000000..d8fa2325b9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionActionTargetDetailsErrorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionActionTargetDetailsError ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionActionTargetDetailsError.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionActionTargetDetailsError.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionActionTargetDetailsError.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.cs new file mode 100644 index 00000000000..abc4bc735e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Experiment action target details error model. + public partial class ExperimentExecutionActionTargetDetailsError : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal + { + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private string _message; + + /// The error message + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal.Message { get => this._message; set { {_message = value;} } } + + /// + /// Creates an new instance. + /// + public ExperimentExecutionActionTargetDetailsError() + { + + } + } + /// Model that represents the Experiment action target details error model. + public partial interface IExperimentExecutionActionTargetDetailsError : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 message + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; } + + } + /// Model that represents the Experiment action target details error model. + internal partial interface IExperimentExecutionActionTargetDetailsErrorInternal + + { + /// The error code. + string Code { get; set; } + /// The error message + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.json.cs new file mode 100644 index 00000000000..a5caa28fbc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsError.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Experiment action target details error model. + public partial class ExperimentExecutionActionTargetDetailsError + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionActionTargetDetailsError(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_code = If( json?.PropertyT("code"), out var __jsonCode) ? (string)__jsonCode : (string)_code;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)_message;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionActionTargetDetailsError(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.PowerShell.cs new file mode 100644 index 00000000000..5ab40cd71a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.PowerShell.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the Experiment action target details properties model. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionActionTargetDetailsPropertiesTypeConverter))] + public partial class ExperimentExecutionActionTargetDetailsProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionActionTargetDetailsProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionActionTargetDetailsProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionActionTargetDetailsProperties(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.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsErrorTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("TargetFailedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetFailedTime = (global::System.DateTime?) content.GetValueForProperty("TargetFailedTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetFailedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TargetCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetCompletedTime = (global::System.DateTime?) content.GetValueForProperty("TargetCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)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 ExperimentExecutionActionTargetDetailsProperties(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.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsErrorTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("TargetFailedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetFailedTime = (global::System.DateTime?) content.GetValueForProperty("TargetFailedTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetFailedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TargetCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetCompletedTime = (global::System.DateTime?) content.GetValueForProperty("TargetCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).TargetCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal)this).Message, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the Experiment action target details properties model. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionActionTargetDetailsPropertiesTypeConverter))] + public partial interface IExperimentExecutionActionTargetDetailsProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.TypeConverter.cs new file mode 100644 index 00000000000..614f5683c60 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionActionTargetDetailsPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionActionTargetDetailsProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionActionTargetDetailsProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionActionTargetDetailsProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.cs new file mode 100644 index 00000000000..3f665e573bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Experiment action target details properties model. + public partial class ExperimentExecutionActionTargetDetailsProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal + { + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)Error).Code; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError _error; + + /// The error of the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsError()); } + + /// The error message + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)Error).Message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)Error).Code = value ?? null; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionActionTargetDetailsError()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsErrorInternal)Error).Message = value ?? null; } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.Status { get => this._status; set { {_status = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.Target { get => this._target; set { {_target = value;} } } + + /// Internal Acessors for TargetCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.TargetCompletedTime { get => this._targetCompletedTime; set { {_targetCompletedTime = value;} } } + + /// Internal Acessors for TargetFailedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsPropertiesInternal.TargetFailedTime { get => this._targetFailedTime; set { {_targetFailedTime = value;} } } + + /// Backing field for property. + private string _status; + + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Backing field for property. + private string _target; + + /// The target for the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Target { get => this._target; } + + /// Backing field for property. + private global::System.DateTime? _targetCompletedTime; + + /// String that represents the completed date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? TargetCompletedTime { get => this._targetCompletedTime; } + + /// Backing field for property. + private global::System.DateTime? _targetFailedTime; + + /// String that represents the failed date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? TargetFailedTime { get => this._targetFailedTime; } + + /// + /// Creates an new instance. + /// + public ExperimentExecutionActionTargetDetailsProperties() + { + + } + } + /// Model that represents the Experiment action target details properties model. + public partial interface IExperimentExecutionActionTargetDetailsProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 message + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the execution.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// The target for the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The target for the action.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + /// String that represents the completed date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the completed date time.", + SerializedName = @"targetCompletedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TargetCompletedTime { get; } + /// String that represents the failed date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the failed date time.", + SerializedName = @"targetFailedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TargetFailedTime { get; } + + } + /// Model that represents the Experiment action target details properties model. + internal partial interface IExperimentExecutionActionTargetDetailsPropertiesInternal + + { + /// The error code. + string Code { get; set; } + /// The error of the action. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsError Error { get; set; } + /// The error message + string Message { get; set; } + /// The status of the execution. + string Status { get; set; } + /// The target for the action. + string Target { get; set; } + /// String that represents the completed date time. + global::System.DateTime? TargetCompletedTime { get; set; } + /// String that represents the failed date time. + global::System.DateTime? TargetFailedTime { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.json.cs new file mode 100644 index 00000000000..65945416382 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionActionTargetDetailsProperties.json.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Experiment action target details properties model. + public partial class ExperimentExecutionActionTargetDetailsProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionActionTargetDetailsProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ExperimentExecutionActionTargetDetailsError.FromJson(__jsonError) : _error;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_target = If( json?.PropertyT("target"), out var __jsonTarget) ? (string)__jsonTarget : (string)_target;} + {_targetFailedTime = If( json?.PropertyT("targetFailedTime"), out var __jsonTargetFailedTime) ? global::System.DateTime.TryParse((string)__jsonTargetFailedTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonTargetFailedTimeValue) ? __jsonTargetFailedTimeValue : _targetFailedTime : _targetFailedTime;} + {_targetCompletedTime = If( json?.PropertyT("targetCompletedTime"), out var __jsonTargetCompletedTime) ? global::System.DateTime.TryParse((string)__jsonTargetCompletedTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonTargetCompletedTimeValue) ? __jsonTargetCompletedTimeValue : _targetCompletedTime : _targetCompletedTime;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionActionTargetDetailsProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionActionTargetDetailsProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._error.ToJson(null,serializationMode) : null, "error" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._targetFailedTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._targetFailedTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "targetFailedTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._targetCompletedTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._targetCompletedTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "targetCompletedTime" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.PowerShell.cs new file mode 100644 index 00000000000..a325a31ddba --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the execution details of an Experiment. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionDetailsTypeConverter))] + public partial class ExperimentExecutionDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionDetails(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionDetails(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionDetails(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.Chaos.Models.IExperimentExecutionDetailsInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("RunInformation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformation = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation) content.GetValueForProperty("RunInformation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformation, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformationTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StoppedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("FailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).FailureReason = (string) content.GetValueForProperty("FailureReason",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).FailureReason, global::System.Convert.ToString); + } + if (content.Contains("LastActionAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).LastActionAt = (global::System.DateTime?) content.GetValueForProperty("LastActionAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).LastActionAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RunInformationStep")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformationStep = (System.Collections.Generic.List) content.GetValueForProperty("RunInformationStep",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformationStep, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatusTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ExperimentExecutionDetails(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.Chaos.Models.IExperimentExecutionDetailsInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("RunInformation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformation = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation) content.GetValueForProperty("RunInformation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformation, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformationTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).StoppedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("FailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).FailureReason = (string) content.GetValueForProperty("FailureReason",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).FailureReason, global::System.Convert.ToString); + } + if (content.Contains("LastActionAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).LastActionAt = (global::System.DateTime?) content.GetValueForProperty("LastActionAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).LastActionAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RunInformationStep")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformationStep = (System.Collections.Generic.List) content.GetValueForProperty("RunInformationStep",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal)this).RunInformationStep, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatusTypeConverter.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.Chaos.Models.IExperimentExecutionDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the execution details of an Experiment. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionDetailsTypeConverter))] + public partial interface IExperimentExecutionDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.TypeConverter.cs new file mode 100644 index 00000000000..33eee480047 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionDetails.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.cs new file mode 100644 index 00000000000..c6fb1a273e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the execution details of an Experiment. + public partial class ExperimentExecutionDetails : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal + { + + /// The reason why the execution failed. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string FailureReason { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).FailureReason; } + + /// Backing field for property. + private string _id; + + /// String of the fully qualified resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// String that represents the last action date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? LastActionAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).LastActionAt; } + + /// Internal Acessors for FailureReason + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.FailureReason { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).FailureReason; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).FailureReason = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for LastActionAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.LastActionAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).LastActionAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).LastActionAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsProperties()); set { {_property = value;} } } + + /// Internal Acessors for RunInformation + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.RunInformation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).RunInformation; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).RunInformation = value ?? null /* model class */; } + + /// Internal Acessors for RunInformationStep + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.RunInformationStep { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).RunInformationStep; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).RunInformationStep = value ?? null /* arrayOf */; } + + /// Internal Acessors for StartedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.StartedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).StartedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).StartedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).Status = value ?? null; } + + /// Internal Acessors for StoppedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.StoppedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).StoppedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).StoppedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// String of the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties _property; + + /// The properties of the experiment execution details. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsProperties()); } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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); } + + /// The steps of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RunInformationStep { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).RunInformationStep; } + + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? StartedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).StartedAt; } + + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).Status; } + + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? StoppedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)Property).StoppedAt; } + + /// Backing field for property. + private string _type; + + /// String of the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ExperimentExecutionDetails() + { + + } + } + /// Model that represents the execution details of an Experiment. + public partial interface IExperimentExecutionDetails : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The reason why the execution failed. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The reason why the execution failed.", + SerializedName = @"failureReason", + PossibleTypes = new [] { typeof(string) })] + string FailureReason { get; } + /// String of the fully qualified resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the fully qualified resource ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// String that represents the last action date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the last action date time.", + SerializedName = @"lastActionAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastActionAt { get; } + /// String of the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the resource name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The steps of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The steps of the experiment run.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus) })] + System.Collections.Generic.List RunInformationStep { get; } + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the start date time.", + SerializedName = @"startedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartedAt { get; } + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the execution.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the stop date time.", + SerializedName = @"stoppedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StoppedAt { get; } + /// String of the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String of the resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Model that represents the execution details of an Experiment. + internal partial interface IExperimentExecutionDetailsInternal + + { + /// The reason why the execution failed. + string FailureReason { get; set; } + /// String of the fully qualified resource ID. + string Id { get; set; } + /// String that represents the last action date time. + global::System.DateTime? LastActionAt { get; set; } + /// String of the resource name. + string Name { get; set; } + /// The properties of the experiment execution details. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties Property { get; set; } + /// The information of the experiment run. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation RunInformation { get; set; } + /// The steps of the experiment run. + System.Collections.Generic.List RunInformationStep { get; set; } + /// String that represents the start date time. + global::System.DateTime? StartedAt { get; set; } + /// The status of the execution. + string Status { get; set; } + /// String that represents the stop date time. + global::System.DateTime? StoppedAt { get; set; } + /// String of the resource type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.json.cs new file mode 100644 index 00000000000..f53e72ff6a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetails.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the execution details of an Experiment. + public partial class ExperimentExecutionDetails + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionDetails(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ExperimentExecutionDetailsProperties.FromJson(__jsonProperties) : _property;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionDetails(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.PowerShell.cs new file mode 100644 index 00000000000..9d2588f63f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.PowerShell.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the extended properties of an experiment execution. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionDetailsPropertiesTypeConverter))] + public partial class ExperimentExecutionDetailsProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionDetailsProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionDetailsProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionDetailsProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionDetailsProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RunInformation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformation = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation) content.GetValueForProperty("RunInformation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformation, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformationTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StoppedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("FailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).FailureReason = (string) content.GetValueForProperty("FailureReason",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).FailureReason, global::System.Convert.ToString); + } + if (content.Contains("LastActionAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).LastActionAt = (global::System.DateTime?) content.GetValueForProperty("LastActionAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).LastActionAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RunInformationStep")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformationStep = (System.Collections.Generic.List) content.GetValueForProperty("RunInformationStep",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformationStep, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatusTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ExperimentExecutionDetailsProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RunInformation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformation = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation) content.GetValueForProperty("RunInformation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformation, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformationTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).StoppedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("FailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).FailureReason = (string) content.GetValueForProperty("FailureReason",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).FailureReason, global::System.Convert.ToString); + } + if (content.Contains("LastActionAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).LastActionAt = (global::System.DateTime?) content.GetValueForProperty("LastActionAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).LastActionAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RunInformationStep")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformationStep = (System.Collections.Generic.List) content.GetValueForProperty("RunInformationStep",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal)this).RunInformationStep, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatusTypeConverter.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.Chaos.Models.IExperimentExecutionDetailsProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the extended properties of an experiment execution. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionDetailsPropertiesTypeConverter))] + public partial interface IExperimentExecutionDetailsProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.TypeConverter.cs new file mode 100644 index 00000000000..22f20a4e178 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionDetailsPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionDetailsProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionDetailsProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionDetailsProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionDetailsProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.cs new file mode 100644 index 00000000000..cf5f1fb945e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.cs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the extended properties of an experiment execution. + public partial class ExperimentExecutionDetailsProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal + { + + /// Backing field for property. + private string _failureReason; + + /// The reason why the execution failed. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string FailureReason { get => this._failureReason; } + + /// Backing field for property. + private global::System.DateTime? _lastActionAt; + + /// String that represents the last action date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? LastActionAt { get => this._lastActionAt; } + + /// Internal Acessors for FailureReason + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.FailureReason { get => this._failureReason; set { {_failureReason = value;} } } + + /// Internal Acessors for LastActionAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.LastActionAt { get => this._lastActionAt; set { {_lastActionAt = value;} } } + + /// Internal Acessors for RunInformation + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.RunInformation { get => (this._runInformation = this._runInformation ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformation()); set { {_runInformation = value;} } } + + /// Internal Acessors for RunInformationStep + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.RunInformationStep { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)RunInformation).Step; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)RunInformation).Step = value ?? null /* arrayOf */; } + + /// Internal Acessors for StartedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.StartedAt { get => this._startedAt; set { {_startedAt = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.Status { get => this._status; set { {_status = value;} } } + + /// Internal Acessors for StoppedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesInternal.StoppedAt { get => this._stoppedAt; set { {_stoppedAt = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation _runInformation; + + /// The information of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation RunInformation { get => (this._runInformation = this._runInformation ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformation()); } + + /// The steps of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RunInformationStep { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)RunInformation).Step; } + + /// Backing field for property. + private global::System.DateTime? _startedAt; + + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StartedAt { get => this._startedAt; } + + /// Backing field for property. + private string _status; + + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Backing field for property. + private global::System.DateTime? _stoppedAt; + + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StoppedAt { get => this._stoppedAt; } + + /// Creates an new instance. + public ExperimentExecutionDetailsProperties() + { + + } + } + /// Model that represents the extended properties of an experiment execution. + public partial interface IExperimentExecutionDetailsProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The reason why the execution failed. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The reason why the execution failed.", + SerializedName = @"failureReason", + PossibleTypes = new [] { typeof(string) })] + string FailureReason { get; } + /// String that represents the last action date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the last action date time.", + SerializedName = @"lastActionAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastActionAt { get; } + /// The steps of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The steps of the experiment run.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus) })] + System.Collections.Generic.List RunInformationStep { get; } + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the start date time.", + SerializedName = @"startedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartedAt { get; } + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the execution.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the stop date time.", + SerializedName = @"stoppedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StoppedAt { get; } + + } + /// Model that represents the extended properties of an experiment execution. + internal partial interface IExperimentExecutionDetailsPropertiesInternal + + { + /// The reason why the execution failed. + string FailureReason { get; set; } + /// String that represents the last action date time. + global::System.DateTime? LastActionAt { get; set; } + /// The information of the experiment run. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation RunInformation { get; set; } + /// The steps of the experiment run. + System.Collections.Generic.List RunInformationStep { get; set; } + /// String that represents the start date time. + global::System.DateTime? StartedAt { get; set; } + /// The status of the execution. + string Status { get; set; } + /// String that represents the stop date time. + global::System.DateTime? StoppedAt { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.json.cs new file mode 100644 index 00000000000..4c5acd69a70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsProperties.json.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the extended properties of an experiment execution. + public partial class ExperimentExecutionDetailsProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionDetailsProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_runInformation = If( json?.PropertyT("runInformation"), out var __jsonRunInformation) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionDetailsPropertiesRunInformation.FromJson(__jsonRunInformation) : _runInformation;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_startedAt = If( json?.PropertyT("startedAt"), out var __jsonStartedAt) ? global::System.DateTime.TryParse((string)__jsonStartedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartedAtValue) ? __jsonStartedAtValue : _startedAt : _startedAt;} + {_stoppedAt = If( json?.PropertyT("stoppedAt"), out var __jsonStoppedAt) ? global::System.DateTime.TryParse((string)__jsonStoppedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStoppedAtValue) ? __jsonStoppedAtValue : _stoppedAt : _stoppedAt;} + {_failureReason = If( json?.PropertyT("failureReason"), out var __jsonFailureReason) ? (string)__jsonFailureReason : (string)_failureReason;} + {_lastActionAt = If( json?.PropertyT("lastActionAt"), out var __jsonLastActionAt) ? global::System.DateTime.TryParse((string)__jsonLastActionAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastActionAtValue) ? __jsonLastActionAtValue : _lastActionAt : _lastActionAt;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionDetailsProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._runInformation ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._runInformation.ToJson(null,serializationMode) : null, "runInformation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._startedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startedAt" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._stoppedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._stoppedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "stoppedAt" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._failureReason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._failureReason.ToString()) : null, "failureReason" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastActionAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._lastActionAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastActionAt" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.PowerShell.cs new file mode 100644 index 00000000000..f073eebb48a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// The information of the experiment run. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionDetailsPropertiesRunInformationTypeConverter))] + public partial class ExperimentExecutionDetailsPropertiesRunInformation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionDetailsPropertiesRunInformation(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionDetailsPropertiesRunInformation(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionDetailsPropertiesRunInformation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Step")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)this).Step = (System.Collections.Generic.List) content.GetValueForProperty("Step",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)this).Step, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatusTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ExperimentExecutionDetailsPropertiesRunInformation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Step")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)this).Step = (System.Collections.Generic.List) content.GetValueForProperty("Step",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal)this).Step, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatusTypeConverter.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.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 information of the experiment run. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionDetailsPropertiesRunInformationTypeConverter))] + public partial interface IExperimentExecutionDetailsPropertiesRunInformation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.TypeConverter.cs new file mode 100644 index 00000000000..be56a645196 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionDetailsPropertiesRunInformationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionDetailsPropertiesRunInformation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionDetailsPropertiesRunInformation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionDetailsPropertiesRunInformation.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.cs new file mode 100644 index 00000000000..6e88f87c38e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The information of the experiment run. + public partial class ExperimentExecutionDetailsPropertiesRunInformation : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal + { + + /// Internal Acessors for Step + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformationInternal.Step { get => this._step; set { {_step = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _step; + + /// The steps of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Step { get => this._step; } + + /// + /// Creates an new instance. + /// + public ExperimentExecutionDetailsPropertiesRunInformation() + { + + } + } + /// The information of the experiment run. + public partial interface IExperimentExecutionDetailsPropertiesRunInformation : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The steps of the experiment run. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The steps of the experiment run.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus) })] + System.Collections.Generic.List Step { get; } + + } + /// The information of the experiment run. + internal partial interface IExperimentExecutionDetailsPropertiesRunInformationInternal + + { + /// The steps of the experiment run. + System.Collections.Generic.List Step { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.json.cs new file mode 100644 index 00000000000..10f369fad35 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionDetailsPropertiesRunInformation.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The information of the experiment run. + public partial class ExperimentExecutionDetailsPropertiesRunInformation + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionDetailsPropertiesRunInformation(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_step = If( json?.PropertyT("steps"), out var __jsonSteps) ? If( __jsonSteps as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IStepStatus) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.StepStatus.FromJson(__u) )) ))() : null : _step;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetailsPropertiesRunInformation FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionDetailsPropertiesRunInformation(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._step) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._step ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("steps",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.PowerShell.cs new file mode 100644 index 00000000000..5f12ed553a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// Model that represents a list of Experiment executions and a link for pagination. + /// + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionListResultTypeConverter))] + public partial class ExperimentExecutionListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionListResult(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.Chaos.Models.IExperimentExecutionListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal)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 ExperimentExecutionListResult(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.Chaos.Models.IExperimentExecutionListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecutionTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal)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.Chaos.Models.IExperimentExecutionListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a list of Experiment executions and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionListResultTypeConverter))] + public partial interface IExperimentExecutionListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.TypeConverter.cs new file mode 100644 index 00000000000..3bf514f9b47 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.cs new file mode 100644 index 00000000000..4801c5c00e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents a list of Experiment executions and a link for pagination. + /// + public partial class ExperimentExecutionListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The ExperimentExecution items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ExperimentExecutionListResult() + { + + } + } + /// Model that represents a list of Experiment executions and a link for pagination. + public partial interface IExperimentExecutionListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 ExperimentExecution items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ExperimentExecution items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Model that represents a list of Experiment executions and a link for pagination. + internal partial interface IExperimentExecutionListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The ExperimentExecution items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.json.cs new file mode 100644 index 00000000000..2d49e797fe5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents a list of Experiment executions and a link for pagination. + /// + public partial class ExperimentExecutionListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentExecution.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.Chaos.Models.IExperimentExecutionListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionListResult(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.PowerShell.cs new file mode 100644 index 00000000000..2c6a8dec299 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the execution properties of an Experiment. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionPropertiesTypeConverter))] + public partial class ExperimentExecutionProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentExecutionProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentExecutionProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentExecutionProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentExecutionProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StoppedAt, (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 ExperimentExecutionProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StartedAt = (global::System.DateTime?) content.GetValueForProperty("StartedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StartedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StoppedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StoppedAt = (global::System.DateTime?) content.GetValueForProperty("StoppedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal)this).StoppedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + 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.Chaos.Models.IExperimentExecutionProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the execution properties of an Experiment. + [System.ComponentModel.TypeConverter(typeof(ExperimentExecutionPropertiesTypeConverter))] + public partial interface IExperimentExecutionProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.TypeConverter.cs new file mode 100644 index 00000000000..4138806afee --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentExecutionPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentExecutionProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentExecutionProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentExecutionProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentExecutionProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.cs new file mode 100644 index 00000000000..c05d6b9f726 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.cs @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the execution properties of an Experiment. + public partial class ExperimentExecutionProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal + { + + /// Internal Acessors for StartedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal.StartedAt { get => this._startedAt; set { {_startedAt = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal.Status { get => this._status; set { {_status = value;} } } + + /// Internal Acessors for StoppedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionPropertiesInternal.StoppedAt { get => this._stoppedAt; set { {_stoppedAt = value;} } } + + /// Backing field for property. + private global::System.DateTime? _startedAt; + + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StartedAt { get => this._startedAt; } + + /// Backing field for property. + private string _status; + + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Backing field for property. + private global::System.DateTime? _stoppedAt; + + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StoppedAt { get => this._stoppedAt; } + + /// Creates an new instance. + public ExperimentExecutionProperties() + { + + } + } + /// Model that represents the execution properties of an Experiment. + public partial interface IExperimentExecutionProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// String that represents the start date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the start date time.", + SerializedName = @"startedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartedAt { get; } + /// The status of the execution. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the execution.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// String that represents the stop date time. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"String that represents the stop date time.", + SerializedName = @"stoppedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StoppedAt { get; } + + } + /// Model that represents the execution properties of an Experiment. + internal partial interface IExperimentExecutionPropertiesInternal + + { + /// String that represents the start date time. + global::System.DateTime? StartedAt { get; set; } + /// The status of the execution. + string Status { get; set; } + /// String that represents the stop date time. + global::System.DateTime? StoppedAt { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.json.cs new file mode 100644 index 00000000000..06a7af6b091 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentExecutionProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the execution properties of an Experiment. + public partial class ExperimentExecutionProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentExecutionProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_startedAt = If( json?.PropertyT("startedAt"), out var __jsonStartedAt) ? global::System.DateTime.TryParse((string)__jsonStartedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartedAtValue) ? __jsonStartedAtValue : _startedAt : _startedAt;} + {_stoppedAt = If( json?.PropertyT("stoppedAt"), out var __jsonStoppedAt) ? global::System.DateTime.TryParse((string)__jsonStoppedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStoppedAtValue) ? __jsonStoppedAtValue : _stoppedAt : _stoppedAt;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentExecutionProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._startedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startedAt" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._stoppedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._stoppedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "stoppedAt" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.PowerShell.cs new file mode 100644 index 00000000000..dc888e5fb63 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a list of Experiment resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(ExperimentListResultTypeConverter))] + public partial class ExperimentListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentListResult(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.Chaos.Models.IExperimentListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal)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 ExperimentListResult(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.Chaos.Models.IExperimentListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal)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.Chaos.Models.IExperimentListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a list of Experiment resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(ExperimentListResultTypeConverter))] + public partial interface IExperimentListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.TypeConverter.cs new file mode 100644 index 00000000000..1fe83f57a96 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.cs new file mode 100644 index 00000000000..b79d5e2c80e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list of Experiment resources and a link for pagination. + public partial class ExperimentListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Experiment items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ExperimentListResult() + { + + } + } + /// Model that represents a list of Experiment resources and a link for pagination. + public partial interface IExperimentListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Experiment items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Experiment items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Model that represents a list of Experiment resources and a link for pagination. + internal partial interface IExperimentListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Experiment items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.json.cs new file mode 100644 index 00000000000..dae8a5fe884 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list of Experiment resources and a link for pagination. + public partial class ExperimentListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperiment) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment.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.Chaos.Models.IExperimentListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentListResult(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.PowerShell.cs new file mode 100644 index 00000000000..a111b38ee35 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the Experiment properties model. + [System.ComponentModel.TypeConverter(typeof(ExperimentPropertiesTypeConverter))] + public partial class ExperimentProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Step")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Step = (System.Collections.Generic.List) content.GetValueForProperty("Step",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Step, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentStepTypeConverter.ConvertFrom)); + } + if (content.Contains("Selector")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Selector = (System.Collections.Generic.List) content.GetValueForProperty("Selector",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Selector, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelectorTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ExperimentProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Step")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Step = (System.Collections.Generic.List) content.GetValueForProperty("Step",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Step, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentStepTypeConverter.ConvertFrom)); + } + if (content.Contains("Selector")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Selector = (System.Collections.Generic.List) content.GetValueForProperty("Selector",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal)this).Selector, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelectorTypeConverter.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.Chaos.Models.IExperimentProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents the Experiment properties model. + [System.ComponentModel.TypeConverter(typeof(ExperimentPropertiesTypeConverter))] + public partial interface IExperimentProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.TypeConverter.cs new file mode 100644 index 00000000000..247ee8229c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.cs new file mode 100644 index 00000000000..fcc8d211e50 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Experiment properties model. + public partial class ExperimentProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal + { + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Most recent provisioning state for the given experiment resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private System.Collections.Generic.List _selector; + + /// List of selectors. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Selector { get => this._selector; set => this._selector = value; } + + /// Backing field for property. + private System.Collections.Generic.List _step; + + /// List of steps. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Step { get => this._step; set => this._step = value; } + + /// Creates an new instance. + public ExperimentProperties() + { + + } + } + /// Model that represents the Experiment properties model. + public partial interface IExperimentProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// Most recent provisioning state for the given experiment resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Most recent provisioning state for the given experiment resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; } + /// List of selectors. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of selectors.", + SerializedName = @"selectors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector) })] + System.Collections.Generic.List Selector { get; set; } + /// List of steps. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of steps.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep) })] + System.Collections.Generic.List Step { get; set; } + + } + /// Model that represents the Experiment properties model. + internal partial interface IExperimentPropertiesInternal + + { + /// Most recent provisioning state for the given experiment resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; set; } + /// List of selectors. + System.Collections.Generic.List Selector { get; set; } + /// List of steps. + System.Collections.Generic.List Step { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.json.cs new file mode 100644 index 00000000000..1f42478ec57 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentProperties.json.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the Experiment properties model. + public partial class ExperimentProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_step = If( json?.PropertyT("steps"), out var __jsonSteps) ? If( __jsonSteps as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IChaosExperimentStep) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosExperimentStep.FromJson(__u) )) ))() : null : _step;} + {_selector = If( json?.PropertyT("selectors"), out var __jsonSelectors) ? If( __jsonSelectors as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IChaosTargetSelector) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ChaosTargetSelector.FromJson(__p) )) ))() : null : _selector;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentProperties(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (null != this._step) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._step ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("steps",__w); + } + if (null != this._selector) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __s in this._selector ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("selectors",__r); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.PowerShell.cs new file mode 100644 index 00000000000..ae0af61d18b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Describes an experiment update. + [System.ComponentModel.TypeConverter(typeof(ExperimentUpdateTypeConverter))] + public partial class ExperimentUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentUpdate(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentUpdate(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.Chaos.Models.IExperimentUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentUpdateTagsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ExperimentUpdate(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.Chaos.Models.IExperimentUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentUpdateTagsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.Chaos.Models.IExperimentUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Describes an experiment update. + [System.ComponentModel.TypeConverter(typeof(ExperimentUpdateTypeConverter))] + public partial interface IExperimentUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.TypeConverter.cs new file mode 100644 index 00000000000..085a138ce1f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.cs new file mode 100644 index 00000000000..6b97fe100fc --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Describes an experiment update. + public partial class ExperimentUpdate : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentUpdateTags()); set => this._tag = value; } + + /// Creates an new instance. + public ExperimentUpdate() + { + + } + } + /// Describes an experiment update. + public partial interface IExperimentUpdate : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags Tag { get; set; } + + } + /// Describes an experiment update. + internal partial interface IExperimentUpdateInternal + + { + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.json.cs new file mode 100644 index 00000000000..57b9fc391c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdate.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Describes an experiment update. + public partial class ExperimentUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ExperimentUpdate(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ExperimentUpdateTags.FromJson(__jsonTags) : _tag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentUpdate(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.PowerShell.cs new file mode 100644 index 00000000000..f937dd2a0fd --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(ExperimentUpdateTagsTypeConverter))] + public partial class ExperimentUpdateTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IExperimentUpdateTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ExperimentUpdateTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ExperimentUpdateTags(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ExperimentUpdateTags(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 ExperimentUpdateTags(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); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(ExperimentUpdateTagsTypeConverter))] + public partial interface IExperimentUpdateTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.TypeConverter.cs new file mode 100644 index 00000000000..603c2af2e6d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ExperimentUpdateTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IExperimentUpdateTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ExperimentUpdateTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ExperimentUpdateTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ExperimentUpdateTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.cs new file mode 100644 index 00000000000..48b4d163087 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Resource tags. + public partial class ExperimentUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTagsInternal + { + + /// Creates an new instance. + public ExperimentUpdateTags() + { + + } + } + /// Resource tags. + public partial interface IExperimentUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface IExperimentUpdateTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.dictionary.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.dictionary.cs new file mode 100644 index 00000000000..9ed32ae088d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + public partial class ExperimentUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ExperimentUpdateTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.json.cs new file mode 100644 index 00000000000..cc0bac2370c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ExperimentUpdateTags.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Resource tags. + public partial class ExperimentUpdateTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ExperimentUpdateTags(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentUpdateTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ExperimentUpdateTags(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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.PowerShell.cs new file mode 100644 index 00000000000..07376f25a5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// A map to describe the settings of an action. + [System.ComponentModel.TypeConverter(typeof(KeyValuePairTypeConverter))] + public partial class KeyValuePair + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IKeyValuePair DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new KeyValuePair(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new KeyValuePair(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal KeyValuePair(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Key")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Key, global::System.Convert.ToString); + } + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Value, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal KeyValuePair(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Key")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Key, global::System.Convert.ToString); + } + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal)this).Value, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 map to describe the settings of an action. + [System.ComponentModel.TypeConverter(typeof(KeyValuePairTypeConverter))] + public partial interface IKeyValuePair + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.TypeConverter.cs new file mode 100644 index 00000000000..5c0c1c1bbe0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class KeyValuePairTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IKeyValuePair ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return KeyValuePair.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return KeyValuePair.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return KeyValuePair.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.cs new file mode 100644 index 00000000000..4945bea353c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// A map to describe the settings of an action. + public partial class KeyValuePair : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePairInternal + { + + /// Backing field for property. + private string _key; + + /// The name of the setting for the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Key { get => this._key; set => this._key = value; } + + /// Backing field for property. + private string _value; + + /// The value of the setting for the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public KeyValuePair() + { + + } + } + /// A map to describe the settings of an action. + public partial interface IKeyValuePair : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The name of the setting for the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the setting for the action.", + SerializedName = @"key", + PossibleTypes = new [] { typeof(string) })] + string Key { get; set; } + /// The value of the setting for the action. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The value of the setting for the action.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(string) })] + string Value { get; set; } + + } + /// A map to describe the settings of an action. + internal partial interface IKeyValuePairInternal + + { + /// The name of the setting for the action. + string Key { get; set; } + /// The value of the setting for the action. + string Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.json.cs new file mode 100644 index 00000000000..f317da78719 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/KeyValuePair.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// A map to describe the settings of an action. + public partial class KeyValuePair + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IKeyValuePair FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new KeyValuePair(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal KeyValuePair(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_key = If( json?.PropertyT("key"), out var __jsonKey) ? (string)__jsonKey : (string)_key;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? (string)__jsonValue : (string)_value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._key)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._key.ToString()) : null, "key" ,container.Add ); + AddIf( null != (((object)this._value)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._value.ToString()) : null, "value" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs new file mode 100644 index 00000000000..4b6fbfb7b92 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IManagedServiceIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.Chaos.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs new file mode 100644 index 00000000000..e63246fc9b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IManagedServiceIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs new file mode 100644 index 00000000000..d89f769777d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities _userAssignedIdentity; + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get => (this._userAssignedIdentity = this._userAssignedIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentities()); 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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities 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.Chaos.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs new file mode 100644 index 00000000000..37fb7ee96ca --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ManagedServiceIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedServiceIdentity(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ManagedServiceIdentityUserAssignedIdentities.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != this._userAssignedIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs new file mode 100644 index 00000000000..7100919a9ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// The identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedServiceIdentityUserAssignedIdentities(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 ManagedServiceIdentityUserAssignedIdentities(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.Chaos.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 identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial interface IManagedServiceIdentityUserAssignedIdentities + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs new file mode 100644 index 00000000000..ab4685d677f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedServiceIdentityUserAssignedIdentitiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedServiceIdentityUserAssignedIdentities.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs new file mode 100644 index 00000000000..a08853722a9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentitiesInternal + { + + /// + /// Creates an new instance. + /// + public ManagedServiceIdentityUserAssignedIdentities() + { + + } + } + /// The identities assigned to this resource by the user. + public partial interface IManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + + } + /// The identities assigned to this resource by the user. + internal partial interface IManagedServiceIdentityUserAssignedIdentitiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs new file mode 100644 index 00000000000..fbb8e258cc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IUserAssignedIdentity value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ManagedServiceIdentityUserAssignedIdentities source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs new file mode 100644 index 00000000000..120813f20da --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IManagedServiceIdentityUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ManagedServiceIdentityUserAssignedIdentities(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedServiceIdentityUserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.UserAssignedIdentity.FromJson(j) ,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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..dc3a2cb3d02 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..6100399cb5e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..ad0994b846f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationDisplay()); set => this._display = value; } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for ActionType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.ActionType { get => this._actionType; set { {_actionType = value;} } } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Description = value ?? null; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Operation = value ?? null; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Provider = value ?? null; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)Display).Resource = value ?? null; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.Chaos.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..1cd76774ebf --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperation. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperation. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..4066ef9584e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..eea7bffb105 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..4b4954c4401 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..a9ce077b43a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..ea7c309dc1d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..80ecbf0edb5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..d25be8b3436 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..5448e04dada --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.PowerShell.cs new file mode 100644 index 00000000000..bf36201115e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// The status of operation. + [System.ComponentModel.TypeConverter(typeof(OperationStatusTypeConverter))] + public partial class OperationStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IOperationStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.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.Chaos.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 status of operation. + [System.ComponentModel.TypeConverter(typeof(OperationStatusTypeConverter))] + public partial interface IOperationStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.TypeConverter.cs new file mode 100644 index 00000000000..20c89ace39b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IOperationStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/OperationStatus.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.cs new file mode 100644 index 00000000000..2703b3cfa75 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The status of operation. + public partial class OperationStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponse __errorResponse = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse(); + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Detail; } + + /// Backing field for property. + private global::System.DateTime? _endTime; + + /// The end time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? EndTime { get => this._endTime; } + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Error { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Error = value ?? null /* model class */; } + + /// Backing field for property. + private string _id; + + /// The operation Id. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Error { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Error = value ?? null /* model class */; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Message = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Target = value ?? null; } + + /// Internal Acessors for EndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal.EndTime { get => this._endTime; set { {_endTime = value;} } } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusInternal.StartTime { get => this._startTime; set { {_startTime = value;} } } + + /// Backing field for property. + private string _name; + + /// The operation name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// The start time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; } + + /// Backing field for property. + private string _status; + + /// The status of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal)__errorResponse).Target; } + + /// Creates an new instance. + public OperationStatus() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__errorResponse), __errorResponse); + await eventListener.AssertObjectIsValid(nameof(__errorResponse), __errorResponse); + } + } + /// The status of operation. + public partial interface IOperationStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponse + { + /// The end time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The end time of the operation.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; } + /// The operation Id. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The operation Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The operation name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The operation name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// The start time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The start time of the operation.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// The status of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The status of the operation.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; set; } + + } + /// The status of operation. + internal partial interface IOperationStatusInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorResponseInternal + { + /// The end time of the operation. + global::System.DateTime? EndTime { get; set; } + /// The operation Id. + string Id { get; set; } + /// The operation name. + string Name { get; set; } + /// The start time of the operation. + global::System.DateTime? StartTime { get; set; } + /// The status of the operation. + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.json.cs new file mode 100644 index 00000000000..11ad67a40b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatus.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The status of operation. + public partial class OperationStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new OperationStatus(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal OperationStatus(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __errorResponse = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorResponse(json); + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? global::System.DateTime.TryParse((string)__jsonEndTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndTimeValue) ? __jsonEndTimeValue : _endTime : _endTime;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + 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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __errorResponse?.ToJson(container, serializationMode); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._endTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._endTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endTime" ,container.Add ); + } + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.PowerShell.cs new file mode 100644 index 00000000000..1990e08ec99 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.PowerShell.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// The current status of an async operation. + [System.ComponentModel.TypeConverter(typeof(OperationStatusResultTypeConverter))] + public partial class OperationStatusResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IOperationStatusResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationStatusResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationStatusResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationStatusResult(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.Chaos.Models.IOperationStatusResultInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("PercentComplete")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).PercentComplete = (double?) content.GetValueForProperty("PercentComplete",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).PercentComplete, (__y)=> (double) global::System.Convert.ChangeType(__y, typeof(double))); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Operation = (System.Collections.Generic.List) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Operation, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationStatusResultTypeConverter.ConvertFrom)); + } + if (content.Contains("ResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).ResourceId = (string) content.GetValueForProperty("ResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).ResourceId, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationStatusResult(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.Chaos.Models.IOperationStatusResultInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("PercentComplete")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).PercentComplete = (double?) content.GetValueForProperty("PercentComplete",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).PercentComplete, (__y)=> (double) global::System.Convert.ChangeType(__y, typeof(double))); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Operation = (System.Collections.Generic.List) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Operation, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationStatusResultTypeConverter.ConvertFrom)); + } + if (content.Contains("ResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).ResourceId = (string) content.GetValueForProperty("ResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).ResourceId, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorAdditionalInfoTypeConverter.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.Chaos.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 current status of an async operation. + [System.ComponentModel.TypeConverter(typeof(OperationStatusResultTypeConverter))] + public partial interface IOperationStatusResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.TypeConverter.cs new file mode 100644 index 00000000000..8a981409d45 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationStatusResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IOperationStatusResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationStatusResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationStatusResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationStatusResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.cs new file mode 100644 index 00000000000..67088dca12b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.cs @@ -0,0 +1,317 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The current status of an async operation. + public partial class OperationStatusResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private global::System.DateTime? _endTime; + + /// The end time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? EndTime { get => this._endTime; set => this._endTime = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail _error; + + /// If present, details of the operation error. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetail()); set => this._error = value; } + + /// Backing field for property. + private string _id; + + /// Fully qualified ID for the async operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Message = value ?? null; } + + /// Internal Acessors for ResourceId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.ResourceId { get => this._resourceId; set { {_resourceId = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResultInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Target = value ?? null; } + + /// Backing field for property. + private string _name; + + /// Name of the async operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private System.Collections.Generic.List _operation; + + /// The operations list. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private double? _percentComplete; + + /// Percent of the operation that is complete. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public double? PercentComplete { get => this._percentComplete; set => this._percentComplete = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 _resourceId; + + /// + /// Fully qualified ID of the resource against which the original async operation was started. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ResourceId { get => this._resourceId; } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// The start time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; set => this._startTime = value; } + + /// Backing field for property. + private string _status; + + /// Operation status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public OperationStatusResult() + { + + } + } + /// The current status of an async operation. + public partial interface IOperationStatusResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The end time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The end time of the operation.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; set; } + /// Fully qualified ID for the async operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Fully qualified ID for the async operation.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; } + /// Name of the async operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the async operation.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// The operations list. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The operations list.", + SerializedName = @"operations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult) })] + System.Collections.Generic.List Operation { get; set; } + /// Percent of the operation that is complete. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Percent of the operation that is complete.", + SerializedName = @"percentComplete", + PossibleTypes = new [] { typeof(double) })] + double? PercentComplete { get; set; } + /// + /// Fully qualified ID of the resource against which the original async operation was started. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Fully qualified ID of the resource against which the original async operation was started.", + SerializedName = @"resourceId", + PossibleTypes = new [] { typeof(string) })] + string ResourceId { get; } + /// The start time of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The start time of the operation.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; set; } + /// Operation status. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Operation status.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; set; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 current status of an async operation. + internal partial interface IOperationStatusResultInternal + + { + /// 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 end time of the operation. + global::System.DateTime? EndTime { get; set; } + /// If present, details of the operation error. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IErrorDetail Error { get; set; } + /// Fully qualified ID for the async operation. + string Id { get; set; } + /// The error message. + string Message { get; set; } + /// Name of the async operation. + string Name { get; set; } + /// The operations list. + System.Collections.Generic.List Operation { get; set; } + /// Percent of the operation that is complete. + double? PercentComplete { get; set; } + /// + /// Fully qualified ID of the resource against which the original async operation was started. + /// + string ResourceId { get; set; } + /// The start time of the operation. + global::System.DateTime? StartTime { get; set; } + /// Operation status. + string Status { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.json.cs new file mode 100644 index 00000000000..1966b9a901d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/OperationStatusResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The current status of an async operation. + public partial class OperationStatusResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperationStatusResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new OperationStatusResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal OperationStatusResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ErrorDetail.FromJson(__jsonError) : _error;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_percentComplete = If( json?.PropertyT("percentComplete"), out var __jsonPercentComplete) ? (double?)__jsonPercentComplete : _percentComplete;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? global::System.DateTime.TryParse((string)__jsonEndTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndTimeValue) ? __jsonEndTimeValue : _endTime : _endTime;} + {_operation = If( json?.PropertyT("operations"), out var __jsonOperations) ? If( __jsonOperations as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IOperationStatusResult) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.OperationStatusResult.FromJson(__u) )) ))() : null : _operation;} + {_resourceId = If( json?.PropertyT("resourceId"), out var __jsonResourceId) ? (string)__jsonResourceId : (string)_resourceId;} + 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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._error.ToJson(null,serializationMode) : null, "error" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + AddIf( null != this._percentComplete ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNumber((double)this._percentComplete) : null, "percentComplete" ,container.Add ); + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + AddIf( null != this._endTime ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._endTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endTime" ,container.Add ); + if (null != this._operation) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._operation ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("operations",__w); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._resourceId.ToString()) : null, "resourceId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs new file mode 100644 index 00000000000..bda5b8b6455 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs new file mode 100644 index 00000000000..741c3e31e3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/ProxyResource.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.cs new file mode 100644 index 00000000000..956a5a808ac --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.json.cs new file mode 100644 index 00000000000..cb4c6e65c75 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/ProxyResource.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..a9db964534f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..ea957302b2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..53009132d3f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Resource.cs @@ -0,0 +1,255 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// 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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..f77cd78b3e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/StepStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.PowerShell.cs new file mode 100644 index 00000000000..80bab1a8e84 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the a list of branches and branch statuses. + [System.ComponentModel.TypeConverter(typeof(StepStatusTypeConverter))] + public partial class StepStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.IStepStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new StepStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new StepStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal StepStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("StepName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepName = (string) content.GetValueForProperty("StepName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepName, global::System.Convert.ToString); + } + if (content.Contains("StepId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepId = (string) content.GetValueForProperty("StepId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Branch")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Branch = (System.Collections.Generic.List) content.GetValueForProperty("Branch",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Branch, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.BranchStatusTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal StepStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("StepName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepName = (string) content.GetValueForProperty("StepName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepName, global::System.Convert.ToString); + } + if (content.Contains("StepId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepId = (string) content.GetValueForProperty("StepId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).StepId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Branch")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Branch = (System.Collections.Generic.List) content.GetValueForProperty("Branch",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal)this).Branch, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.BranchStatusTypeConverter.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.Chaos.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(); + } + } + /// Model that represents the a list of branches and branch statuses. + [System.ComponentModel.TypeConverter(typeof(StepStatusTypeConverter))] + public partial interface IStepStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.TypeConverter.cs new file mode 100644 index 00000000000..bd134c5de8c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class StepStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IStepStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return StepStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return StepStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return StepStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/StepStatus.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.cs new file mode 100644 index 00000000000..96ea25f5f3e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the a list of branches and branch statuses. + public partial class StepStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _branch; + + /// The array of branches. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Branch { get => this._branch; } + + /// Internal Acessors for Branch + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal.Branch { get => this._branch; set { {_branch = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal.Status { get => this._status; set { {_status = value;} } } + + /// Internal Acessors for StepId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal.StepId { get => this._stepId; set { {_stepId = value;} } } + + /// Internal Acessors for StepName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatusInternal.StepName { get => this._stepName; set { {_stepName = value;} } } + + /// Backing field for property. + private string _status; + + /// The value of the status of the step. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Backing field for property. + private string _stepId; + + /// The id of the step. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string StepId { get => this._stepId; } + + /// Backing field for property. + private string _stepName; + + /// The name of the step. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string StepName { get => this._stepName; } + + /// Creates an new instance. + public StepStatus() + { + + } + } + /// Model that represents the a list of branches and branch statuses. + public partial interface IStepStatus : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The array of branches. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The array of branches.", + SerializedName = @"branches", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IBranchStatus) })] + System.Collections.Generic.List Branch { get; } + /// The value of the status of the step. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The value of the status of the step.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; } + /// The id of the step. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The id of the step.", + SerializedName = @"stepId", + PossibleTypes = new [] { typeof(string) })] + string StepId { get; } + /// The name of the step. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the step.", + SerializedName = @"stepName", + PossibleTypes = new [] { typeof(string) })] + string StepName { get; } + + } + /// Model that represents the a list of branches and branch statuses. + internal partial interface IStepStatusInternal + + { + /// The array of branches. + System.Collections.Generic.List Branch { get; set; } + /// The value of the status of the step. + string Status { get; set; } + /// The id of the step. + string StepId { get; set; } + /// The name of the step. + string StepName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.json.cs new file mode 100644 index 00000000000..5ca08bd975b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/StepStatus.json.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the a list of branches and branch statuses. + public partial class StepStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IStepStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new StepStatus(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal StepStatus(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_stepName = If( json?.PropertyT("stepName"), out var __jsonStepName) ? (string)__jsonStepName : (string)_stepName;} + {_stepId = If( json?.PropertyT("stepId"), out var __jsonStepId) ? (string)__jsonStepId : (string)_stepId;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_branch = If( json?.PropertyT("branches"), out var __jsonBranches) ? If( __jsonBranches as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IBranchStatus) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.BranchStatus.FromJson(__u) )) ))() : null : _branch;} + 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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._stepName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._stepName.ToString()) : null, "stepName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._stepId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._stepId.ToString()) : null, "stepId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._branch) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._branch ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("branches",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..f01a3928537 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..02c39c001ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..dc9c92d015e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..8b456932983 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/Target.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.PowerShell.cs new file mode 100644 index 00000000000..d1f43a41c85 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a Target resource. + [System.ComponentModel.TypeConverter(typeof(TargetTypeConverter))] + public partial class Target + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITarget DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Target(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Target(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Target(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.Chaos.Models.ITargetInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Target(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.Chaos.Models.ITargetInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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(); + } + } + /// Model that represents a Target resource. + [System.ComponentModel.TypeConverter(typeof(TargetTypeConverter))] + public partial interface ITarget + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.TypeConverter.cs new file mode 100644 index 00000000000..0432fdd1c1b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITarget ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Target.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Target.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Target.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/Target.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.cs new file mode 100644 index 00000000000..6a986b835b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Target resource. + public partial class Target : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; } + + /// Backing field for property. + private string _location; + + /// Azure resource location. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties _property; + + /// The properties of the target resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetProperties()); set => this._property = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public Target() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Model that represents a Target resource. + public partial interface ITarget : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource + { + /// Azure resource location. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure resource location.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The properties of the target resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The properties of the target resource.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties Property { get; set; } + + } + /// Model that represents a Target resource. + internal partial interface ITargetInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResourceInternal + { + /// Azure resource location. + string Location { get; set; } + /// The properties of the target resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties Property { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.json.cs new file mode 100644 index 00000000000..9ed34dec825 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/Target.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Target resource. + public partial class Target + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new Target(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal Target(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetProperties.FromJson(__jsonProperties) : _property;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.PowerShell.cs new file mode 100644 index 00000000000..47bdcfa4c81 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a list of Target resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(TargetListResultTypeConverter))] + public partial class TargetListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITargetListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TargetListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TargetListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TargetListResult(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.Chaos.Models.ITargetListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal)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 TargetListResult(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.Chaos.Models.ITargetListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal)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.Chaos.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(); + } + } + /// Model that represents a list of Target resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(TargetListResultTypeConverter))] + public partial interface ITargetListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.TypeConverter.cs new file mode 100644 index 00000000000..e0815b7a318 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITargetListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TargetListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TargetListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TargetListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/TargetListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.cs new file mode 100644 index 00000000000..8243f4e39f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list of Target resources and a link for pagination. + public partial class TargetListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Target items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public TargetListResult() + { + + } + } + /// Model that represents a list of Target resources and a link for pagination. + public partial interface ITargetListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Target items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Target items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Model that represents a list of Target resources and a link for pagination. + internal partial interface ITargetListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Target items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.json.cs new file mode 100644 index 00000000000..7b94bb643fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a list of Target resources and a link for pagination. + public partial class TargetListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TargetListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal TargetListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITarget) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/TargetProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.PowerShell.cs new file mode 100644 index 00000000000..a8ee7f19f3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// The properties of the target resource. + [System.ComponentModel.TypeConverter(typeof(TargetPropertiesTypeConverter))] + public partial class TargetProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITargetProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TargetProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TargetProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TargetProperties(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 TargetProperties(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.Chaos.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 properties of the target resource. + [System.ComponentModel.TypeConverter(typeof(TargetPropertiesTypeConverter))] + public partial interface ITargetProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.TypeConverter.cs new file mode 100644 index 00000000000..6626eaf4252 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITargetProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TargetProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TargetProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TargetProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/TargetProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.cs new file mode 100644 index 00000000000..30f148a0705 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The properties of the target resource. + public partial class TargetProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetPropertiesInternal + { + + /// Creates an new instance. + public TargetProperties() + { + + } + } + /// The properties of the target resource. + public partial interface ITargetProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + + } + /// The properties of the target resource. + internal partial interface ITargetPropertiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.dictionary.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.dictionary.cs new file mode 100644 index 00000000000..d25a441da49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + public partial class TargetProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public global::System.Object this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, global::System.Object 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.Chaos.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.Chaos.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 global::System.Object value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetProperties source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.json.cs new file mode 100644 index 00000000000..aec26403ed2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// The properties of the target resource. + public partial class TargetProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TargetProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TargetProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.JsonSerializable.DeserializeDictionary(()=>new global::System.Collections.Generic.Dictionary()),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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.PowerShell.cs new file mode 100644 index 00000000000..5d0c413a511 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a reference to a Target in the selector. + [System.ComponentModel.TypeConverter(typeof(TargetReferenceTypeConverter))] + public partial class TargetReference + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITargetReference DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TargetReference(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TargetReference(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TargetReference(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.Chaos.Models.ITargetReferenceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal)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 TargetReference(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.Chaos.Models.ITargetReferenceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal)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.Chaos.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(); + } + } + /// Model that represents a reference to a Target in the selector. + [System.ComponentModel.TypeConverter(typeof(TargetReferenceTypeConverter))] + public partial interface ITargetReference + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.TypeConverter.cs new file mode 100644 index 00000000000..5115b5a1c9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetReferenceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITargetReference ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TargetReference.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TargetReference.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TargetReference.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/TargetReference.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.cs new file mode 100644 index 00000000000..fa3f6ffcd3c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a reference to a Target in the selector. + public partial class TargetReference : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal + { + + /// Backing field for property. + private string _id; + + /// String of the resource ID of a Target resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReferenceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type= @"ChaosTarget"; + + /// Enum of the Target reference type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public TargetReference() + { + + } + } + /// Model that represents a reference to a Target in the selector. + public partial interface ITargetReference : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// String of the resource ID of a Target resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"String of the resource ID of a Target resource.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Enum of the Target reference type. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = true, + Read = true, + Create = true, + Update = true, + Description = @"Enum of the Target reference type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Model that represents a reference to a Target in the selector. + internal partial interface ITargetReferenceInternal + + { + /// String of the resource ID of a Target resource. + string Id { get; set; } + /// Enum of the Target reference type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.json.cs new file mode 100644 index 00000000000..3b5e3e5e559 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetReference.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a reference to a Target in the selector. + public partial class TargetReference + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetReference FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TargetReference(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal TargetReference(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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;} + {_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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/TargetType.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.PowerShell.cs new file mode 100644 index 00000000000..d9ed16d8934 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.PowerShell.cs @@ -0,0 +1,274 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents a Target Type resource. + [System.ComponentModel.TypeConverter(typeof(TargetTypeTypeConverter))] + public partial class TargetType + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITargetType DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TargetType(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TargetType(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TargetType(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.Chaos.Models.ITargetTypeInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("PropertiesSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).PropertiesSchema = (string) content.GetValueForProperty("PropertiesSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).PropertiesSchema, global::System.Convert.ToString); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).ResourceType = (System.Collections.Generic.List) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).ResourceType, __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 TargetType(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.Chaos.Models.ITargetTypeInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("PropertiesSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).PropertiesSchema = (string) content.GetValueForProperty("PropertiesSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).PropertiesSchema, global::System.Convert.ToString); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).ResourceType = (System.Collections.Generic.List) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal)this).ResourceType, __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.Chaos.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(); + } + } + /// Model that represents a Target Type resource. + [System.ComponentModel.TypeConverter(typeof(TargetTypeTypeConverter))] + public partial interface ITargetType + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.TypeConverter.cs new file mode 100644 index 00000000000..08a39f13476 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetTypeTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITargetType ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TargetType.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TargetType.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TargetType.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/TargetType.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.cs new file mode 100644 index 00000000000..72223c36e31 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.cs @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Target Type resource. + public partial class TargetType : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(); + + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).Description; } + + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).DisplayName; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal.Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).Description = value ?? null; } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal.DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).DisplayName = value ?? null; } + + /// Internal Acessors for PropertiesSchema + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal.PropertiesSchema { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).PropertiesSchema; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).PropertiesSchema = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeProperties()); set { {_property = value;} } } + + /// Internal Acessors for ResourceType + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeInternal.ResourceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).ResourceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).ResourceType = value ?? null /* arrayOf */; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Name; } + + /// URL to retrieve JSON schema of the Target Type properties. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public string PropertiesSchema { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).PropertiesSchema; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties _property; + + /// The properties of the target type resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeProperties()); set => this._property = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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); } + + /// List of resource types this Target Type can extend. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inlined)] + public System.Collections.Generic.List ResourceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)Property).ResourceType; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public TargetType() + { + + } + + /// 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.Chaos.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Model that represents a Target Type resource. + public partial interface ITargetType : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResource + { + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// URL to retrieve JSON schema of the Target Type properties. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to retrieve JSON schema of the Target Type properties.", + SerializedName = @"propertiesSchema", + PossibleTypes = new [] { typeof(string) })] + string PropertiesSchema { get; } + /// List of resource types this Target Type can extend. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of resource types this Target Type can extend.", + SerializedName = @"resourceTypes", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List ResourceType { get; } + + } + /// Model that represents a Target Type resource. + internal partial interface ITargetTypeInternal : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IProxyResourceInternal + { + /// Localized string of the description. + string Description { get; set; } + /// Localized string of the display name. + string DisplayName { get; set; } + /// URL to retrieve JSON schema of the Target Type properties. + string PropertiesSchema { get; set; } + /// The properties of the target type resource. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties Property { get; set; } + /// List of resource types this Target Type can extend. + System.Collections.Generic.List ResourceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.json.cs new file mode 100644 index 00000000000..227993c0439 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetType.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents a Target Type resource. + public partial class TargetType + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TargetType(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal TargetType(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeProperties.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.PowerShell.cs new file mode 100644 index 00000000000..2d8065d04f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// Model that represents a list of Target Type resources and a link for pagination. + /// + [System.ComponentModel.TypeConverter(typeof(TargetTypeListResultTypeConverter))] + public partial class TargetTypeListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITargetTypeListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TargetTypeListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TargetTypeListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TargetTypeListResult(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.Chaos.Models.ITargetTypeListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal)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 TargetTypeListResult(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.Chaos.Models.ITargetTypeListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetTypeTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal)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.Chaos.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(); + } + } + /// Model that represents a list of Target Type resources and a link for pagination. + [System.ComponentModel.TypeConverter(typeof(TargetTypeListResultTypeConverter))] + public partial interface ITargetTypeListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.TypeConverter.cs new file mode 100644 index 00000000000..7c885104e59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetTypeListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITargetTypeListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TargetTypeListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TargetTypeListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TargetTypeListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.cs new file mode 100644 index 00000000000..3dc1a3b8939 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents a list of Target Type resources and a link for pagination. + /// + public partial class TargetTypeListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The TargetType items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public TargetTypeListResult() + { + + } + } + /// Model that represents a list of Target Type resources and a link for pagination. + public partial interface ITargetTypeListResult : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 TargetType items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The TargetType items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Model that represents a list of Target Type resources and a link for pagination. + internal partial interface ITargetTypeListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The TargetType items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.json.cs new file mode 100644 index 00000000000..1829b72c481 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeListResult.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// + /// Model that represents a list of Target Type resources and a link for pagination. + /// + public partial class TargetTypeListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TargetTypeListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal TargetTypeListResult(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITargetType) (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TargetType.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.PowerShell.cs new file mode 100644 index 00000000000..ccae2c6ed25 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Model that represents the base Target Type properties model. + [System.ComponentModel.TypeConverter(typeof(TargetTypePropertiesTypeConverter))] + public partial class TargetTypeProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Chaos.Models.ITargetTypeProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TargetTypeProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TargetTypeProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TargetTypeProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("PropertiesSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).PropertiesSchema = (string) content.GetValueForProperty("PropertiesSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).PropertiesSchema, global::System.Convert.ToString); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).ResourceType = (System.Collections.Generic.List) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).ResourceType, __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 TargetTypeProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("PropertiesSchema")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).PropertiesSchema = (string) content.GetValueForProperty("PropertiesSchema",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).PropertiesSchema, global::System.Convert.ToString); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).ResourceType = (System.Collections.Generic.List) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal)this).ResourceType, __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.Chaos.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(); + } + } + /// Model that represents the base Target Type properties model. + [System.ComponentModel.TypeConverter(typeof(TargetTypePropertiesTypeConverter))] + public partial interface ITargetTypeProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.TypeConverter.cs new file mode 100644 index 00000000000..f463f373769 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TargetTypePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITargetTypeProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TargetTypeProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TargetTypeProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TargetTypeProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.cs new file mode 100644 index 00000000000..115d65da5aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the base Target Type properties model. + public partial class TargetTypeProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal + { + + /// Backing field for property. + private string _description; + + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Backing field for property. + private string _displayName; + + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal.DisplayName { get => this._displayName; set { {_displayName = value;} } } + + /// Internal Acessors for PropertiesSchema + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal.PropertiesSchema { get => this._propertiesSchema; set { {_propertiesSchema = value;} } } + + /// Internal Acessors for ResourceType + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypePropertiesInternal.ResourceType { get => this._resourceType; set { {_resourceType = value;} } } + + /// Backing field for property. + private string _propertiesSchema; + + /// URL to retrieve JSON schema of the Target Type properties. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string PropertiesSchema { get => this._propertiesSchema; } + + /// Backing field for property. + private System.Collections.Generic.List _resourceType; + + /// List of resource types this Target Type can extend. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public System.Collections.Generic.List ResourceType { get => this._resourceType; } + + /// Creates an new instance. + public TargetTypeProperties() + { + + } + } + /// Model that represents the base Target Type properties model. + public partial interface ITargetTypeProperties : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable + { + /// Localized string of the description. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// Localized string of the display name. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Localized string of the display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// URL to retrieve JSON schema of the Target Type properties. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to retrieve JSON schema of the Target Type properties.", + SerializedName = @"propertiesSchema", + PossibleTypes = new [] { typeof(string) })] + string PropertiesSchema { get; } + /// List of resource types this Target Type can extend. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of resource types this Target Type can extend.", + SerializedName = @"resourceTypes", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List ResourceType { get; } + + } + /// Model that represents the base Target Type properties model. + internal partial interface ITargetTypePropertiesInternal + + { + /// Localized string of the description. + string Description { get; set; } + /// Localized string of the display name. + string DisplayName { get; set; } + /// URL to retrieve JSON schema of the Target Type properties. + string PropertiesSchema { get; set; } + /// List of resource types this Target Type can extend. + System.Collections.Generic.List ResourceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.json.cs new file mode 100644 index 00000000000..e4b2b2fe990 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TargetTypeProperties.json.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Model that represents the base Target Type properties model. + public partial class TargetTypeProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetTypeProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TargetTypeProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal TargetTypeProperties(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_propertiesSchema = If( json?.PropertyT("propertiesSchema"), out var __jsonPropertiesSchema) ? (string)__jsonPropertiesSchema : (string)_propertiesSchema;} + {_resourceType = If( json?.PropertyT("resourceTypes"), out var __jsonResourceTypes) ? If( __jsonResourceTypes as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _resourceType;} + 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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._propertiesSchema)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._propertiesSchema.ToString()) : null, "propertiesSchema" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._resourceType) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.XNodeArray(); + foreach( var __x in this._resourceType ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("resourceTypes",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..a30c5ec1a80 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..af102ceabd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..74407bdf720 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResourceTags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + 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.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags 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.Chaos.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..08de6c2054d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.TrackedResourceTags.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/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs new file mode 100644 index 00000000000..17794211f21 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial class TrackedResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// 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.Chaos.Models.ITrackedResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 TrackedResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial interface ITrackedResourceTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs new file mode 100644 index 00000000000..d321c1113f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// 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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.ITrackedResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.cs new file mode 100644 index 00000000000..472dbeb99e3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTagsInternal + { + + /// Creates an new instance. + public TrackedResourceTags() + { + + } + } + /// Resource tags. + public partial interface ITrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITrackedResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs new file mode 100644 index 00000000000..d108e557ff0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.TrackedResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs new file mode 100644 index 00000000000..f278b38d458 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json ? new TrackedResourceTags(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TrackedResourceTags(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs new file mode 100644 index 00000000000..07ece438548 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IUserAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs new file mode 100644 index 00000000000..73d5232e6a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Chaos.Models.IUserAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs new file mode 100644 index 00000000000..f764b4dfcba --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentityInternal + { + + /// Backing field for property. + private string _clientId; + + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentityInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Origin(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IJsonSerializable + { + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs new file mode 100644 index 00000000000..f0d594ebb1a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IUserAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_Get.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_Get.cs new file mode 100644 index 00000000000..f5ffc074e99 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_Get.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability Type resource for given Target Type and location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: CapabilityType + /// variant: Get + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapabilityType_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability Type resource for given Target Type and location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapabilityType_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability Type resource name.", + SerializedName = @"capabilityTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityTypeName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetTypeName; + + /// String that represents a Target Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target Type resource name.", + SerializedName = @"targetTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetTypeName { get => this._targetTypeName; set => this._targetTypeName = 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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapabilityType_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilityTypesGet(SubscriptionId, Location, TargetTypeName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location,TargetTypeName=TargetTypeName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Models.ICapabilityType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentity.cs new file mode 100644 index 00000000000..53427ffd575 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability Type resource for given Target Type and location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: CapabilityType + /// variant: GetViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapabilityType_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability Type resource for given Target Type and location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapabilityType_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapabilityType_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CapabilityTypesGetViaIdentity(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.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetTypeName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetTypeName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.CapabilityTypeName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.CapabilityTypeName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CapabilityTypesGet(InputObject.SubscriptionId ?? null, InputObject.Location ?? null, InputObject.TargetTypeName ?? null, InputObject.CapabilityTypeName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Models.ICapabilityType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentityLocation.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentityLocation.cs new file mode 100644 index 00000000000..c120662b212 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentityLocation.cs @@ -0,0 +1,514 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability Type resource for given Target Type and location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: CapabilityType + /// variant: GetViaIdentityLocation + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapabilityType_GetViaIdentityLocation")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability Type resource for given Target Type and location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapabilityType_GetViaIdentityLocation : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _locationInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity LocationInputObject { get => this._locationInputObject; set => this._locationInputObject = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability Type resource name.", + SerializedName = @"capabilityTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityTypeName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _targetTypeName; + + /// String that represents a Target Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target Type resource name.", + SerializedName = @"targetTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetTypeName { get => this._targetTypeName; set => this._targetTypeName = 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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapabilityType_GetViaIdentityLocation() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (LocationInputObject?.Id != null) + { + this.LocationInputObject.Id += $"/targetTypes/{(global::System.Uri.EscapeDataString(this.TargetTypeName.ToString()))}/capabilityTypes/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.CapabilityTypesGetViaIdentity(LocationInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == LocationInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + if (null == LocationInputObject.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + await this.Client.CapabilityTypesGet(LocationInputObject.SubscriptionId ?? null, LocationInputObject.Location ?? null, TargetTypeName, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { TargetTypeName=TargetTypeName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Models.ICapabilityType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentityTargetType.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentityTargetType.cs new file mode 100644 index 00000000000..e1fa1133f69 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_GetViaIdentityTargetType.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability Type resource for given Target Type and location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: CapabilityType + /// variant: GetViaIdentityTargetType + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapabilityType_GetViaIdentityTargetType")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability Type resource for given Target Type and location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapabilityType_GetViaIdentityTargetType : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability Type resource name.", + SerializedName = @"capabilityTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityTypeName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _targetTypeInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity TargetTypeInputObject { get => this._targetTypeInputObject; set => this._targetTypeInputObject = 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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapabilityType_GetViaIdentityTargetType() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (TargetTypeInputObject?.Id != null) + { + this.TargetTypeInputObject.Id += $"/capabilityTypes/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.CapabilityTypesGetViaIdentity(TargetTypeInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == TargetTypeInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetTypeInputObject has null value for TargetTypeInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetTypeInputObject) ); + } + if (null == TargetTypeInputObject.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetTypeInputObject has null value for TargetTypeInputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetTypeInputObject) ); + } + if (null == TargetTypeInputObject.TargetTypeName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetTypeInputObject has null value for TargetTypeInputObject.TargetTypeName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetTypeInputObject) ); + } + await this.Client.CapabilityTypesGet(TargetTypeInputObject.SubscriptionId ?? null, TargetTypeInputObject.Location ?? null, TargetTypeInputObject.TargetTypeName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapabilityType + /// 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.Chaos.Models.ICapabilityType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_List.cs new file mode 100644 index 00000000000..0ea49fdba70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapabilityType_List.cs @@ -0,0 +1,551 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of Capability Type resources for given Target Type and location. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: CapabilityType + /// variant: List + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapabilityType_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapabilityType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of Capability Type resources for given Target Type and location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapabilityType_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// String that sets the continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "String that sets the continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"String that sets the continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetTypeName; + + /// String that represents a Target Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target Type resource name.", + SerializedName = @"targetTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetTypeName { get => this._targetTypeName; set => this._targetTypeName = 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.Chaos.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.Chaos.Models.ICapabilityTypeListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapabilityType_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilityTypesList(SubscriptionId, Location, TargetTypeName, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location,TargetTypeName=TargetTypeName,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapabilityTypeListResult + /// 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.Chaos.Models.ICapabilityTypeListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilityTypesList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_Get.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_Get.cs new file mode 100644 index 00000000000..c3e1a398287 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_Get.cs @@ -0,0 +1,567 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability resource that extends a Target resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: Get + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapability_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapability_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapability_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesGet(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,TargetName=TargetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_GetViaIdentity.cs new file mode 100644 index 00000000000..6f90335b9d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_GetViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability resource that extends a Target resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: GetViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapability_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapability_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapability_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CapabilitiesGetViaIdentity(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.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.CapabilityName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.CapabilityName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CapabilitiesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, InputObject.CapabilityName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_GetViaIdentityTarget.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_GetViaIdentityTarget.cs new file mode 100644 index 00000000000..9c2b9011698 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_GetViaIdentityTarget.cs @@ -0,0 +1,516 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Capability resource that extends a Target resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: GetViaIdentityTarget + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapability_GetViaIdentityTarget")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapability_GetViaIdentityTarget : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _targetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity TargetInputObject { get => this._targetInputObject; set => this._targetInputObject = 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapability_GetViaIdentityTarget() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (TargetInputObject?.Id != null) + { + this.TargetInputObject.Id += $"/capabilities/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.CapabilitiesGetViaIdentity(TargetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == TargetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + await this.Client.CapabilitiesGet(TargetInputObject.SubscriptionId ?? null, TargetInputObject.ResourceGroupName ?? null, TargetInputObject.ParentProviderNamespace ?? null, TargetInputObject.ParentResourceType ?? null, TargetInputObject.ParentResourceName ?? null, TargetInputObject.TargetName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_List.cs new file mode 100644 index 00000000000..ecbfe97fd85 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosCapability_List.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of Capability resources that extend a Target resource. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: List + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosCapability_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of Capability resources that extend a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities", ApiVersion = "2025-01-01")] + public partial class GetAzChaosCapability_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// String that sets the continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "String that sets the continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"String that sets the continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.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.Chaos.Models.ICapabilityListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosCapability_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesList(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null,TargetName=TargetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ICapabilityListResult + /// 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.Chaos.Models.ICapabilityListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_Execution.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_Execution.cs new file mode 100644 index 00000000000..4aa01780bfd --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_Execution.cs @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Execution details of an experiment resource. + /// + /// [OpenAPI] ExecutionDetails=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExecutionExperimentDetail + /// variant: Execution + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExecutionExperimentDetail_Execution", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Execution details of an experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExecutionExperimentDetail_Execution : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _executionId; + + /// GUID that represents a Experiment execution detail. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "GUID that represents a Experiment execution detail.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"GUID that represents a Experiment execution detail.", + SerializedName = @"executionId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExecutionId { get => this._executionId; set => this._executionId = value; } + + /// Backing field for property. + private string _experimentName; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExperimentName { get => this._experimentName; set => this._experimentName = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionDetails + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExecutionExperimentDetail_Execution() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsExecutionDetails' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsExecutionDetails(SubscriptionId, ResourceGroupName, ExperimentName, ExecutionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ExperimentName=ExperimentName,ExecutionId=ExecutionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionDetails + /// 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.Chaos.Models.IExperimentExecutionDetails + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_ExecutionViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_ExecutionViaIdentity.cs new file mode 100644 index 00000000000..4074e91d03a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_ExecutionViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Execution details of an experiment resource. + /// + /// [OpenAPI] ExecutionDetails=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExecutionExperimentDetail + /// variant: ExecutionViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExecutionExperimentDetail_ExecutionViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Execution details of an experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExecutionExperimentDetail_ExecutionViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionDetails + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExecutionExperimentDetail_ExecutionViaIdentity() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsExecutionDetails' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ExperimentsExecutionDetailsViaIdentity(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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ExecutionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExecutionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ExperimentsExecutionDetails(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, InputObject.ExecutionId ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionDetails + /// 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.Chaos.Models.IExperimentExecutionDetails + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_ExecutionViaIdentityExperiment.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_ExecutionViaIdentityExperiment.cs new file mode 100644 index 00000000000..363a325a409 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExecutionExperimentDetail_ExecutionViaIdentityExperiment.cs @@ -0,0 +1,507 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Execution details of an experiment resource. + /// + /// [OpenAPI] ExecutionDetails=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExecutionExperimentDetail + /// variant: ExecutionViaIdentityExperiment + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExecutionExperimentDetail_ExecutionViaIdentityExperiment", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecutionDetails))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Execution details of an experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExecutionExperimentDetail_ExecutionViaIdentityExperiment : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _executionId; + + /// GUID that represents a Experiment execution detail. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "GUID that represents a Experiment execution detail.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"GUID that represents a Experiment execution detail.", + SerializedName = @"executionId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExecutionId { get => this._executionId; set => this._executionId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _experimentInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity ExperimentInputObject { get => this._experimentInputObject; set => this._experimentInputObject = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionDetails + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExecutionExperimentDetail_ExecutionViaIdentityExperiment() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsExecutionDetails' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ExperimentInputObject?.Id != null) + { + this.ExperimentInputObject.Id += $"/executions/{(global::System.Uri.EscapeDataString(this.ExecutionId.ToString()))}"; + await this.Client.ExperimentsExecutionDetailsViaIdentity(ExperimentInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ExperimentInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ExperimentInputObject has null value for ExperimentInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ExperimentInputObject) ); + } + if (null == ExperimentInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ExperimentInputObject has null value for ExperimentInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ExperimentInputObject) ); + } + if (null == ExperimentInputObject.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ExperimentInputObject has null value for ExperimentInputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ExperimentInputObject) ); + } + await this.Client.ExperimentsExecutionDetails(ExperimentInputObject.SubscriptionId ?? null, ExperimentInputObject.ResourceGroupName ?? null, ExperimentInputObject.ExperimentName ?? null, ExecutionId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ExecutionId=ExecutionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionDetails + /// 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.Chaos.Models.IExperimentExecutionDetails + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_Get.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_Get.cs new file mode 100644 index 00000000000..921523a6116 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_Get.cs @@ -0,0 +1,524 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get an execution of an Experiment resource. + /// + /// [OpenAPI] GetExecution=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExperimentExecution + /// variant: Get + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperimentExecution_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get an execution of an Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperimentExecution_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _executionId; + + /// GUID that represents a Experiment execution detail. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "GUID that represents a Experiment execution detail.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"GUID that represents a Experiment execution detail.", + SerializedName = @"executionId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExecutionId { get => this._executionId; set => this._executionId = value; } + + /// Backing field for property. + private string _experimentName; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExperimentName { get => this._experimentName; set => this._experimentName = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperimentExecution_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsGetExecution(SubscriptionId, ResourceGroupName, ExperimentName, ExecutionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ExperimentName=ExperimentName,ExecutionId=ExecutionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution + /// 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.Chaos.Models.IExperimentExecution + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_GetViaIdentity.cs new file mode 100644 index 00000000000..1b04f452251 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_GetViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get an execution of an Experiment resource. + /// + /// [OpenAPI] GetExecution=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExperimentExecution + /// variant: GetViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperimentExecution_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get an execution of an Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperimentExecution_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperimentExecution_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ExperimentsGetExecutionViaIdentity(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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ExecutionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExecutionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ExperimentsGetExecution(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, InputObject.ExecutionId ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution + /// 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.Chaos.Models.IExperimentExecution + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_GetViaIdentityExperiment.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_GetViaIdentityExperiment.cs new file mode 100644 index 00000000000..bc7abc4e0cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_GetViaIdentityExperiment.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get an execution of an Experiment resource. + /// + /// [OpenAPI] GetExecution=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExperimentExecution + /// variant: GetViaIdentityExperiment + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperimentExecution_GetViaIdentityExperiment")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get an execution of an Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperimentExecution_GetViaIdentityExperiment : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _executionId; + + /// GUID that represents a Experiment execution detail. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "GUID that represents a Experiment execution detail.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"GUID that represents a Experiment execution detail.", + SerializedName = @"executionId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExecutionId { get => this._executionId; set => this._executionId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _experimentInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity ExperimentInputObject { get => this._experimentInputObject; set => this._experimentInputObject = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperimentExecution_GetViaIdentityExperiment() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ExperimentInputObject?.Id != null) + { + this.ExperimentInputObject.Id += $"/executions/{(global::System.Uri.EscapeDataString(this.ExecutionId.ToString()))}"; + await this.Client.ExperimentsGetExecutionViaIdentity(ExperimentInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ExperimentInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ExperimentInputObject has null value for ExperimentInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ExperimentInputObject) ); + } + if (null == ExperimentInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ExperimentInputObject has null value for ExperimentInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ExperimentInputObject) ); + } + if (null == ExperimentInputObject.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ExperimentInputObject has null value for ExperimentInputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ExperimentInputObject) ); + } + await this.Client.ExperimentsGetExecution(ExperimentInputObject.SubscriptionId ?? null, ExperimentInputObject.ResourceGroupName ?? null, ExperimentInputObject.ExperimentName ?? null, ExecutionId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ExecutionId=ExecutionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecution + /// 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.Chaos.Models.IExperimentExecution + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_List.cs new file mode 100644 index 00000000000..70026a70530 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperimentExecution_List.cs @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of executions of an Experiment resource. + /// + /// [OpenAPI] ListAllExecutions=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: ExperimentExecution + /// variant: List + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperimentExecution_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperimentExecution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of executions of an Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperimentExecution_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _experimentName; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ExperimentName { get => this._experimentName; set => this._experimentName = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperimentExecution_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsListAllExecutions(SubscriptionId, ResourceGroupName, ExperimentName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ExperimentName=ExperimentName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentExecutionListResult + /// 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.Chaos.Models.IExperimentExecutionListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsListAllExecutions_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_Get.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_Get.cs new file mode 100644 index 00000000000..42dfda0b794 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_Get.cs @@ -0,0 +1,511 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Experiment resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: Get + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperiment_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperiment_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperiment_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_GetViaIdentity.cs new file mode 100644 index 00000000000..523f9cae40a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Experiment resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: GetViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperiment_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperiment_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperiment_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ExperimentsGetViaIdentity(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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ExperimentsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_List.cs new file mode 100644 index 00000000000..beca55107ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_List.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of Experiment resources in a resource group. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: List + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperiment_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of Experiment resources in a resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperiment_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// String that sets the continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "String that sets the continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"String that sets the continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private global::System.Management.Automation.SwitchParameter _running; + + /// + /// Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then + /// the results will not be filtered. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then the results will not be filtered.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then the results will not be filtered.", + SerializedName = @"running", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public global::System.Management.Automation.SwitchParameter Running { get => this._running; set => this._running = 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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperiment_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsList(SubscriptionId, ResourceGroupName, this.InvocationInformation.BoundParameters.ContainsKey("Running") ? Running : default(global::System.Management.Automation.SwitchParameter?), this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,Running=this.InvocationInformation.BoundParameters.ContainsKey("Running") ? Running : default(global::System.Management.Automation.SwitchParameter?),ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentListResult + /// 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.Chaos.Models.IExperimentListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_List1.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_List1.cs new file mode 100644 index 00000000000..bcd930d8fd4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosExperiment_List1.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of Experiment resources in a subscription. + /// + /// [OpenAPI] ListAll=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/experiments" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: List1 + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosExperiment_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of Experiment resources in a subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/experiments", ApiVersion = "2025-01-01")] + public partial class GetAzChaosExperiment_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// String that sets the continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "String that sets the continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"String that sets the continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private global::System.Management.Automation.SwitchParameter _running; + + /// + /// Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then + /// the results will not be filtered. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then the results will not be filtered.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Optional value that indicates whether to filter results based on if the Experiment is currently running. If null, then the results will not be filtered.", + SerializedName = @"running", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public global::System.Management.Automation.SwitchParameter Running { get => this._running; set => this._running = 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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperimentListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosExperiment_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsListAll(SubscriptionId, this.InvocationInformation.BoundParameters.ContainsKey("Running") ? Running : default(global::System.Management.Automation.SwitchParameter?), this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Running=this.InvocationInformation.BoundParameters.ContainsKey("Running") ? Running : default(global::System.Management.Automation.SwitchParameter?),ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperimentListResult + /// 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.Chaos.Models.IExperimentListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsListAll_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosOperation_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosOperation_List.cs new file mode 100644 index 00000000000..1a8bf716e49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosOperation_List.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Microsoft.Chaos/operations" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Operation + /// variant: List + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/providers/Microsoft.Chaos/operations", ApiVersion = "2025-01-01")] + public partial class GetAzChaosOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosOperation_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_Get.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_Get.cs new file mode 100644 index 00000000000..ca1f3851c2a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_Get.cs @@ -0,0 +1,511 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Target Type resources for given location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: TargetType + /// variant: Get + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTargetType_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Target Type resources for given location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTargetType_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target Type resource name.", + SerializedName = @"targetTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetTypeName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITargetType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTargetType_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetTypesGet(SubscriptionId, Location, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITargetType + /// 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.Chaos.Models.ITargetType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_GetViaIdentity.cs new file mode 100644 index 00000000000..c15e4da4095 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Target Type resources for given location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: TargetType + /// variant: GetViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTargetType_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Target Type resources for given location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTargetType_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITargetType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTargetType_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.TargetTypesGetViaIdentity(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.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetTypeName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetTypeName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.TargetTypesGet(InputObject.SubscriptionId ?? null, InputObject.Location ?? null, InputObject.TargetTypeName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITargetType + /// 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.Chaos.Models.ITargetType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_GetViaIdentityLocation.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_GetViaIdentityLocation.cs new file mode 100644 index 00000000000..d9d4418e56a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_GetViaIdentityLocation.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Target Type resources for given location. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: TargetType + /// variant: GetViaIdentityLocation + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTargetType_GetViaIdentityLocation")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Target Type resources for given location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTargetType_GetViaIdentityLocation : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _locationInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity LocationInputObject { get => this._locationInputObject; set => this._locationInputObject = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target Type resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target Type resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target Type resource name.", + SerializedName = @"targetTypeName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetTypeName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITargetType + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTargetType_GetViaIdentityLocation() + { + + } + + /// 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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (LocationInputObject?.Id != null) + { + this.LocationInputObject.Id += $"/targetTypes/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.TargetTypesGetViaIdentity(LocationInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == LocationInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + if (null == LocationInputObject.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + await this.Client.TargetTypesGet(LocationInputObject.SubscriptionId ?? null, LocationInputObject.Location ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITargetType + /// 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.Chaos.Models.ITargetType + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_List.cs new file mode 100644 index 00000000000..5fa0f367014 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTargetType_List.cs @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of Target Type resources for given location. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: TargetType + /// variant: List + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTargetType_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetType))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of Target Type resources for given location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTargetType_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// String that sets the continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "String that sets the continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"String that sets the continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITargetTypeListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTargetType_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetTypesList(SubscriptionId, Location, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITargetTypeListResult + /// 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.Chaos.Models.ITargetTypeListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetTypesList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_Get.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_Get.cs new file mode 100644 index 00000000000..50313467fe3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_Get.cs @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Target + /// variant: Get + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTarget_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTarget_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTarget_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsGet(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_GetViaIdentity.cs new file mode 100644 index 00000000000..afa7235ba64 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_GetViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Target + /// variant: GetViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTarget_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTarget_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTarget_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.TargetsGetViaIdentity(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.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.TargetsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_List.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_List.cs new file mode 100644 index 00000000000..ede8f824e98 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/GetAzChaosTarget_List.cs @@ -0,0 +1,579 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Get a list of Target resources that extend a tracked regional resource. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets" + /// [DETAILS] + /// verb: Get + /// subjectPrefix: Chaos + /// subject: Target + /// variant: List + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzChaosTarget_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Get a list of Target resources that extend a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets", ApiVersion = "2025-01-01")] + public partial class GetAzChaosTarget_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// String that sets the continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "String that sets the continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"String that sets the continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.ITargetListResult + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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 GetAzChaosTarget_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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsList(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.ITargetListResult + /// 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.Chaos.Models.ITargetListResult + 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.Chaos.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateExpanded.cs new file mode 100644 index 00000000000..bc6a103cb95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateExpanded.cs @@ -0,0 +1,624 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Capability resource that extends a Target resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: CreateExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosCapability_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class NewAzChaosCapability_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Capability resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosCapability_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesCreateOrUpdate(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,TargetName=TargetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaIdentityTargetExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaIdentityTargetExpanded.cs new file mode 100644 index 00000000000..755b44b7aba --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaIdentityTargetExpanded.cs @@ -0,0 +1,576 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Capability resource that extends a Target resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: CreateViaIdentityTargetExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosCapability_CreateViaIdentityTargetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class NewAzChaosCapability_CreateViaIdentityTargetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Capability resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _targetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity TargetInputObject { get => this._targetInputObject; set => this._targetInputObject = 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.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosCapability_CreateViaIdentityTargetExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (TargetInputObject?.Id != null) + { + this.TargetInputObject.Id += $"/capabilities/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.CapabilitiesCreateOrUpdateViaIdentity(TargetInputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == TargetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + await this.Client.CapabilitiesCreateOrUpdate(TargetInputObject.SubscriptionId ?? null, TargetInputObject.ResourceGroupName ?? null, TargetInputObject.ParentProviderNamespace ?? null, TargetInputObject.ParentResourceType ?? null, TargetInputObject.ParentResourceName ?? null, TargetInputObject.TargetName ?? null, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..21616533916 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaJsonFilePath.cs @@ -0,0 +1,637 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Capability resource that extends a Target resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: CreateViaJsonFilePathViaJsonFilePath + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosCapability_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.NotSuggestDefaultParameterSet] + public partial class NewAzChaosCapability_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosCapability_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,TargetName=TargetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaJsonString.cs new file mode 100644 index 00000000000..5c9222a8e93 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosCapability_CreateViaJsonString.cs @@ -0,0 +1,635 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Capability resource that extends a Target resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: CreateViaJsonStringViaJsonString + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosCapability_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.NotSuggestDefaultParameterSet] + public partial class NewAzChaosCapability_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosCapability_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,TargetName=TargetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateExpanded.cs new file mode 100644 index 00000000000..5bbdbcc8d36 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateExpanded.cs @@ -0,0 +1,651 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Experiment resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: CreateExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosExperiment_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + public partial class NewAzChaosExperiment_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// Model that represents a Experiment resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of selectors. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "List of selectors.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"List of selectors.", + SerializedName = @"selectors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector),typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector),typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector[] Selector { get => _resourceBody.Selector?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.Selector = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// List of steps. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "List of steps.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"List of steps.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep[] Step { get => _resourceBody.Step?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.Step = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags 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; } + + /// + /// 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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzChaosExperiment_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.NewAzChaosExperiment_CreateExpanded Clone() + { + var clone = new NewAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosExperiment_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.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.ExperimentsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..e388299091d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateViaJsonFilePath.cs @@ -0,0 +1,579 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Experiment resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: CreateViaJsonFilePathViaJsonFilePath + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosExperiment_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.NotSuggestDefaultParameterSet] + public partial class NewAzChaosExperiment_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + public global::System.String _jsonString; + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzChaosExperiment_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.NewAzChaosExperiment_CreateViaJsonFilePath Clone() + { + var clone = new NewAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosExperiment_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateViaJsonString.cs new file mode 100644 index 00000000000..4d2a6ea204e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosExperiment_CreateViaJsonString.cs @@ -0,0 +1,577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Experiment resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: CreateViaJsonStringViaJsonString + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosExperiment_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.NotSuggestDefaultParameterSet] + public partial class NewAzChaosExperiment_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzChaosExperiment_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.NewAzChaosExperiment_CreateViaJsonString Clone() + { + var clone = new NewAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosExperiment_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateExpanded.cs new file mode 100644 index 00000000000..ce4f4ca11d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateExpanded.cs @@ -0,0 +1,633 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Target + /// variant: CreateExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosTarget_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + public partial class NewAzChaosTarget_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Target resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 resource location. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure resource location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure resource location.", + 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpPipeline Pipeline { get; set; } + + /// The properties of the target resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The properties of the target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The properties of the target resource.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties Property { get => _resourceBody.Property ?? null /* object */; set => _resourceBody.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget + /// 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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosTarget_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsCreateOrUpdate(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..02c9eca047f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateViaJsonFilePath.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Target + /// variant: CreateViaJsonFilePathViaJsonFilePath + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosTarget_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.NotSuggestDefaultParameterSet] + public partial class NewAzChaosTarget_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget + /// 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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosTarget_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateViaJsonString.cs new file mode 100644 index 00000000000..c1c094f8053 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/NewAzChaosTarget_CreateViaJsonString.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// create a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: New + /// subjectPrefix: Chaos + /// subject: Target + /// variant: CreateViaJsonStringViaJsonString + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzChaosTarget_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"create a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.NotSuggestDefaultParameterSet] + public partial class NewAzChaosTarget_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget + /// 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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 NewAzChaosTarget_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_Delete.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_Delete.cs new file mode 100644 index 00000000000..a35100b7918 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_Delete.cs @@ -0,0 +1,588 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Capability that extends a Target resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: Delete + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosCapability_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Capability that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosCapability_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CapabilitiesDelete(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,TargetName=TargetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosCapability_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_DeleteViaIdentity.cs new file mode 100644 index 00000000000..7045ef7c536 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_DeleteViaIdentity.cs @@ -0,0 +1,528 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Capability that extends a Target resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: DeleteViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosCapability_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Capability that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosCapability_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CapabilitiesDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.CapabilityName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.CapabilityName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CapabilitiesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, InputObject.CapabilityName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosCapability_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_DeleteViaIdentityTarget.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_DeleteViaIdentityTarget.cs new file mode 100644 index 00000000000..9459e2f12aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosCapability_DeleteViaIdentityTarget.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Capability that extends a Target resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: DeleteViaIdentityTarget + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosCapability_DeleteViaIdentityTarget", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Capability that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosCapability_DeleteViaIdentityTarget : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _targetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity TargetInputObject { get => this._targetInputObject; set => this._targetInputObject = 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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (TargetInputObject?.Id != null) + { + this.TargetInputObject.Id += $"/capabilities/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.CapabilitiesDeleteViaIdentity(TargetInputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == TargetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + await this.Client.CapabilitiesDelete(TargetInputObject.SubscriptionId ?? null, TargetInputObject.ResourceGroupName ?? null, TargetInputObject.ParentProviderNamespace ?? null, TargetInputObject.ParentResourceType ?? null, TargetInputObject.ParentResourceName ?? null, TargetInputObject.TargetName ?? null, Name, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosCapability_DeleteViaIdentityTarget() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosExperiment_Delete.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosExperiment_Delete.cs new file mode 100644 index 00000000000..e7392aa9591 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosExperiment_Delete.cs @@ -0,0 +1,600 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Experiment resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: Delete + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosExperiment_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosExperiment_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzChaosExperiment_Delete + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.RemoveAzChaosExperiment_Delete Clone() + { + var clone = new RemoveAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsDelete(SubscriptionId, ResourceGroupName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosExperiment_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosExperiment_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosExperiment_DeleteViaIdentity.cs new file mode 100644 index 00000000000..961bfbd936d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosExperiment_DeleteViaIdentity.cs @@ -0,0 +1,577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Experiment resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: DeleteViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosExperiment_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosExperiment_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzChaosExperiment_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.RemoveAzChaosExperiment_DeleteViaIdentity Clone() + { + var clone = new RemoveAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ExperimentsDeleteViaIdentity(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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ExperimentsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosExperiment_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosTarget_Delete.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosTarget_Delete.cs new file mode 100644 index 00000000000..10ca09297bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosTarget_Delete.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Target + /// variant: Delete + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosTarget_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosTarget_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.TargetsDelete(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosTarget_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosTarget_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosTarget_DeleteViaIdentity.cs new file mode 100644 index 00000000000..26a1085eed3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/RemoveAzChaosTarget_DeleteViaIdentity.cs @@ -0,0 +1,524 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Delete a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Remove + /// subjectPrefix: Chaos + /// subject: Target + /// variant: DeleteViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzChaosTarget_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Delete a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}", ApiVersion = "2025-01-01")] + public partial class RemoveAzChaosTarget_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.TargetsDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.TargetsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzChaosTarget_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StartAzChaosExperiment_Start.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StartAzChaosExperiment_Start.cs new file mode 100644 index 00000000000..f3833d10d72 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StartAzChaosExperiment_Start.cs @@ -0,0 +1,566 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Start a Experiment resource. + /// + /// [OpenAPI] Start=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/start" + /// [DETAILS] + /// verb: Start + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: Start + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Start, @"AzChaosExperiment_Start", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Start a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/start", ApiVersion = "2025-01-01")] + public partial class StartAzChaosExperiment_Start : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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. + /// /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StartAzChaosExperiment_Start + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.StartAzChaosExperiment_Start Clone() + { + var clone = new StartAzChaosExperiment_Start(); + 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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsStart' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsStart(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StartAzChaosExperiment_Start() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StartAzChaosExperiment_StartViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StartAzChaosExperiment_StartViaIdentity.cs new file mode 100644 index 00000000000..aeb35396b13 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StartAzChaosExperiment_StartViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Start a Experiment resource. + /// + /// [OpenAPI] Start=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/start" + /// [DETAILS] + /// verb: Start + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: StartViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Start, @"AzChaosExperiment_StartViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Start a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/start", ApiVersion = "2025-01-01")] + public partial class StartAzChaosExperiment_StartViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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. + /// /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StartAzChaosExperiment_StartViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.StartAzChaosExperiment_StartViaIdentity Clone() + { + var clone = new StartAzChaosExperiment_StartViaIdentity(); + 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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsStart' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ExperimentsStartViaIdentity(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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ExperimentsStart(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StartAzChaosExperiment_StartViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StopAzChaosExperiment_Cancel.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StopAzChaosExperiment_Cancel.cs new file mode 100644 index 00000000000..6f65b781a79 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StopAzChaosExperiment_Cancel.cs @@ -0,0 +1,566 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Cancel a running Experiment resource. + /// + /// [OpenAPI] Cancel=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/cancel" + /// [DETAILS] + /// verb: Stop + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: Cancel + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Stop, @"AzChaosExperiment_Cancel", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Cancel a running Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/cancel", ApiVersion = "2025-01-01")] + public partial class StopAzChaosExperiment_Cancel : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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. + /// /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StopAzChaosExperiment_Cancel + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.StopAzChaosExperiment_Cancel Clone() + { + var clone = new StopAzChaosExperiment_Cancel(); + 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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCancel' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ExperimentsCancel(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StopAzChaosExperiment_Cancel() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StopAzChaosExperiment_CancelViaIdentity.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StopAzChaosExperiment_CancelViaIdentity.cs new file mode 100644 index 00000000000..964fbc5a753 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/StopAzChaosExperiment_CancelViaIdentity.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// Cancel a running Experiment resource. + /// + /// [OpenAPI] Cancel=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/cancel" + /// [DETAILS] + /// verb: Stop + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: CancelViaIdentity + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Stop, @"AzChaosExperiment_CancelViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"Cancel a running Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/cancel", ApiVersion = "2025-01-01")] + public partial class StopAzChaosExperiment_CancelViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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. + /// /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StopAzChaosExperiment_CancelViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.StopAzChaosExperiment_CancelViaIdentity Clone() + { + var clone = new StopAzChaosExperiment_CancelViaIdentity(); + 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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCancel' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ExperimentsCancelViaIdentity(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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ExperimentsCancel(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StopAzChaosExperiment_CancelViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateExpanded.cs new file mode 100644 index 00000000000..fb5bc70c13d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateExpanded.cs @@ -0,0 +1,636 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Capability resource that extends a Target resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: UpdateExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: UpdateExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosCapability_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosCapability_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Capability resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _targetName; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string TargetName { get => this._targetName; set => this._targetName = 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.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.CapabilitiesGetWithResult(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CapabilitiesCreateOrUpdate(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, TargetName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,TargetName=TargetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosCapability_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..fa3681a93d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateViaIdentityExpanded.cs @@ -0,0 +1,578 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Capability resource that extends a Target resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: UpdateViaIdentityExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: UpdateViaIdentityExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosCapability_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosCapability_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Capability resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.CapabilitiesGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CapabilitiesCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.CapabilityName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.CapabilityName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.CapabilitiesGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, InputObject.CapabilityName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CapabilitiesCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, InputObject.CapabilityName ?? null, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosCapability_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateViaIdentityTargetExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateViaIdentityTargetExpanded.cs new file mode 100644 index 00000000000..001541f7e30 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosCapability_UpdateViaIdentityTargetExpanded.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Capability resource that extends a Target resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: UpdateViaIdentityTargetExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Capability + /// variant: UpdateViaIdentityTargetExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosCapability_UpdateViaIdentityTargetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Capability resource that extends a Target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosCapability_UpdateViaIdentityTargetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Capability resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ICapability _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Capability(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Capability resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Capability resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Capability resource name.", + SerializedName = @"capabilityName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("CapabilityName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _targetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity TargetInputObject { get => this._targetInputObject; set => this._targetInputObject = 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.Chaos.Models.ICapability + /// 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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CapabilitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (TargetInputObject?.Id != null) + { + this.TargetInputObject.Id += $"/capabilities/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.CapabilitiesGetViaIdentityWithResult(TargetInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CapabilitiesCreateOrUpdateViaIdentity(TargetInputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == TargetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + if (null == TargetInputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("TargetInputObject has null value for TargetInputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, TargetInputObject) ); + } + _resourceBody = await this.Client.CapabilitiesGetWithResult(TargetInputObject.SubscriptionId ?? null, TargetInputObject.ResourceGroupName ?? null, TargetInputObject.ParentProviderNamespace ?? null, TargetInputObject.ParentResourceType ?? null, TargetInputObject.ParentResourceName ?? null, TargetInputObject.TargetName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CapabilitiesCreateOrUpdate(TargetInputObject.SubscriptionId ?? null, TargetInputObject.ResourceGroupName ?? null, TargetInputObject.ParentProviderNamespace ?? null, TargetInputObject.ParentResourceType ?? null, TargetInputObject.ParentResourceName ?? null, TargetInputObject.TargetName ?? null, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosCapability_UpdateViaIdentityTargetExpanded() + { + + } + + private void Update_resourceBody() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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.Chaos.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.Chaos.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.Chaos.Models.ICapability + /// 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.Chaos.Models.ICapability + 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/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosExperiment_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosExperiment_UpdateExpanded.cs new file mode 100644 index 00000000000..954bd8e1462 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosExperiment_UpdateExpanded.cs @@ -0,0 +1,676 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Experiment resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: UpdateExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: UpdateExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosExperiment_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosExperiment_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// Model that represents a Experiment resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Experiment resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Experiment resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Experiment resource name.", + SerializedName = @"experimentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ExperimentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of selectors. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of selectors.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of selectors.", + SerializedName = @"selectors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector),typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector),typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector[] Selector { get => _resourceBody.Selector?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.Selector = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// List of steps. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of steps.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of steps.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep[] Step { get => _resourceBody.Step?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.Step = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags 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; } + + /// + /// 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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzChaosExperiment_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.UpdateAzChaosExperiment_UpdateExpanded Clone() + { + var clone = new UpdateAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.ExperimentsGetWithResult(SubscriptionId, ResourceGroupName, Name, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.ExperimentsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosExperiment_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Step"))) + { + this.Step = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep[])(this.MyInvocation?.BoundParameters["Step"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Selector"))) + { + this.Selector = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector[])(this.MyInvocation?.BoundParameters["Selector"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosExperiment_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosExperiment_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..a986426c627 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosExperiment_UpdateViaIdentityExpanded.cs @@ -0,0 +1,656 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Experiment resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: UpdateViaIdentityExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Experiment + /// variant: UpdateViaIdentityExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosExperiment_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Experiment resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosExperiment_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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(); + + /// Model that represents a Experiment resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IExperiment _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Experiment(); + + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// List of selectors. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of selectors.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of selectors.", + SerializedName = @"selectors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector),typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetListSelector),typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetQuerySelector) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector[] Selector { get => _resourceBody.Selector?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.Selector = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// List of steps. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of steps.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of steps.", + SerializedName = @"steps", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep[] Step { get => _resourceBody.Step?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.Step = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags 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; } + + /// + /// 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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzChaosExperiment_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets.UpdateAzChaosExperiment_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzChaosExperiment_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ExperimentsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.ExperimentsGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.ExperimentsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.ExperimentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ExperimentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.ExperimentsGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.ExperimentsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ExperimentName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosExperiment_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITrackedResourceTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Step"))) + { + this.Step = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosExperimentStep[])(this.MyInvocation?.BoundParameters["Step"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Selector"))) + { + this.Selector = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosTargetSelector[])(this.MyInvocation?.BoundParameters["Selector"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Models.IExperiment + /// 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.Chaos.Models.IExperiment + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosTarget_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosTarget_UpdateExpanded.cs new file mode 100644 index 00000000000..4c075f8de1f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosTarget_UpdateExpanded.cs @@ -0,0 +1,652 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Target + /// variant: UpdateExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Target + /// variant: UpdateExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosTarget_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosTarget_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Target resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 resource location. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure resource location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure resource location.", + 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// String that represents a Target resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "String that represents a Target resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"String that represents a Target resource name.", + SerializedName = @"targetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("TargetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _parentProviderNamespace; + + /// The parent resource provider namespace. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource provider namespace.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource provider namespace.", + SerializedName = @"parentProviderNamespace", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentProviderNamespace { get => this._parentProviderNamespace; set => this._parentProviderNamespace = value; } + + /// Backing field for property. + private string _parentResourceName; + + /// The parent resource name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource name.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource name.", + SerializedName = @"parentResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceName { get => this._parentResourceName; set => this._parentResourceName = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The parent resource type. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parent resource type.")] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parent resource type.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpPipeline Pipeline { get; set; } + + /// The properties of the target resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The properties of the target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The properties of the target resource.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties Property { get => _resourceBody.Property ?? null /* object */; set => _resourceBody.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget + /// 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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.TargetsGetWithResult(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.TargetsCreateOrUpdate(SubscriptionId, ResourceGroupName, ParentProviderNamespace, ParentResourceType, ParentResourceName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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,ParentProviderNamespace=ParentProviderNamespace,ParentResourceType=ParentResourceType,ParentResourceName=ParentResourceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosTarget_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Location"))) + { + this.Location = (string)(this.MyInvocation?.BoundParameters["Location"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosTarget_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosTarget_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..6e5e5af25a9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/cmdlets/UpdateAzChaosTarget_UpdateViaIdentityExpanded.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.Chaos.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Cmdlets; + using System; + + /// update a Target resource that extends a tracked regional resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Target + /// variant: UpdateViaIdentityExpanded + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" + /// [DETAILS] + /// verb: Update + /// subjectPrefix: Chaos + /// subject: Target + /// variant: UpdateViaIdentityExpanded + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzChaosTarget_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Description(@"update a Target resource that extends a tracked regional resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Generated] + public partial class UpdateAzChaosTarget_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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; + + /// Model that represents a Target resource. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.Target(); + + /// + /// 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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.ChaosManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.IChaosIdentity 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 resource location. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure resource location.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure resource location.", + 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.Chaos.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.HttpPipeline Pipeline { get; set; } + + /// The properties of the target resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The properties of the target resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The properties of the target resource.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties) })] + public Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties Property { get => _resourceBody.Property ?? null /* object */; set => _resourceBody.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Chaos.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITarget + /// 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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'TargetsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.TargetsGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.TargetsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.ParentProviderNamespace) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentProviderNamespace"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceType) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceType"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ParentResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ParentResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.TargetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.TargetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.TargetsGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.TargetsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ParentProviderNamespace ?? null, InputObject.ParentResourceType ?? null, InputObject.ParentResourceName ?? null, InputObject.TargetName ?? null, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzChaosTarget_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.Chaos.Models.ITargetProperties)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Location"))) + { + this.Location = (string)(this.MyInvocation?.BoundParameters["Location"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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.Chaos.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.Chaos.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.Chaos.Models.ITarget + /// 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.Chaos.Models.ITarget + 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/Chaos.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..a7c597e67d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..c1581f80a91 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..c329af08dec --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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/Chaos.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..dbb22c7126e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos +{ + 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/Chaos.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..e596038d573 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos +{ + 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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..0cbc2fab2a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..6f864977555 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..7ee61ac01d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..db9be7c9dc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..d0a6865f3b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..45da2e89bf1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..f07eb3254ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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: Chaos 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.Chaos.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.Chaos.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 Chaos".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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..7a8f72299d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..e5bf9e78836 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..8d9fc1ef0e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..61542da7285 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..a5a9fa89020 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..03b83c2c4f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..2a34efd9c7e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..d5c8d646325 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..55b7a80a292 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,211 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.Chaos.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 static string CapitalizeFirstLetter(string text) + { + if (string.IsNullOrEmpty(text)) + return text; + + return char.ToUpper(text[0]) + text.Substring(1); + } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = CapitalizeFirstLetter(helpObject.GetProperty("Synopsis")); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + Description = CapitalizeFirstLetter(Description); + 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/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..dc898520da0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..aab5da4b478 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,681 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.Chaos.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetLoginVerification() + { + if (!VariantGroup.IsInternal && IsAzure && !VariantGroup.IsModelCmdlet) + { + return $@" +{Indent}{Indent}$context = Get-AzContext +{Indent}{Indent}if (-not $context -and -not $testPlayback) {{ +{Indent}{Indent}{Indent}Write-Error ""No Azure login detected. Please run 'Connect-AzAccount' to log in."" +{Indent}{Indent}{Indent}exit +{Indent}{Indent}}} +"; + } + return ""; + } + + 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.Chaos.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 +{Indent}{Indent} +{Indent}{Indent}$testPlayback = $false +{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }} +{GetLoginVerification()}{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}if ($wrappedCmd -eq $null) {{ +{Indent}{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Function) +{Indent}{Indent}}} +{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}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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..e12088dc24c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,549 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.Chaos.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 bool IsModelCmdlet { 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; + IsModelCmdlet = Variants.All(v => v.IsModelCmdlet); + 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 IsModelCmdlet { 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(); + IsModelCmdlet = 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(); + Description = PsHelpInfo.CapitalizeFirstLetter(Description); + // 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/Chaos.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..27d1ebedcc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,136 @@ +/*--------------------------------------------------------------------------------------------- + * 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.Chaos +{ + [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 | AttributeTargets.Property)] + public class ModelCmdletAttribute : 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/Chaos.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..34ae523fe95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..3070bca8029 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..53c3e5064ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..87904daa9a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..a81957203fa --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..8bfd3437380 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParameters, 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.Chaos.ChaosManagementClient Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..50f614d510b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..608cc800a90 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..d3ef3ef287c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..5c775e346ef --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..5c1028790a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..edeebd1f11e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..b1e088e1d06 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..23e048134cd --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..ce0691a2aef --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..ebe331b86f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..a46d48df70e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..a55aefbee5e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..de0df292e38 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..b03244538cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..1d4c45153f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..3d3c44a6509 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..401a88bb12a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..e646e575a0b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..2bb99b14aa6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..e657a2b0a03 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..412de4a6205 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..77f93b66370 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..ec372557d2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..a4907e1886d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..00f9ca76931 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..9363bc0243a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..04ce099fd28 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..694a4649671 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..a2ecd24b2e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..2daed429147 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..5d95e0149c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..0d8ee77f908 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..8657c3d5b7a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..b1c6baf0ee6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..39bd6907671 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..4f22bcf644c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..50549745bd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..7f1fd752df5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..c17a11a20b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..970dae7f5af --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..5185548258e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..e58eb5adb9f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..09b7a8903de --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..7a2c4604adc --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..a54dc671fea --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..d6e8f09892a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..e9bd0ce8a97 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..fc1b8426e7e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..22b339e7c53 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..433e8ee2814 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..5f3be12824e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..9d7f1b29342 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..44132ed05ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..514ad58e71c --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..82d397f1f0a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..e01e4a62b0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..87551b64f5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..67c852d20e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,353 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Chaos.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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 description of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //Name of the module that is being deprecated + public string moduleName { get; set; } = String.IsNullOrEmpty(@"") ? @"Az.Chaos" : @""; + + //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.moduleName, 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/Chaos.Management.brown/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..6a03c6d61a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..aeb74f7e3a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..f98c5f734d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..37bf9b75ee0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..ae0154c6d7b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..1e416a5e367 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..65e7d1a2c15 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..e83273a7385 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..55abe69fc90 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..75a111d5001 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..7cd871cd7e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..e195a6bafe1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..09013d04503 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..052e76d679f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..7b653df239f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..317d098bd10 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..f6fc22c7301 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..809a2719c5a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..1a16d01c6ce --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..5f078a6df61 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..6aa8fcbf920 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..943f4ef4ad8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..028dd98af12 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..1fe80a568f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..4435dfdc52e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..7c98c92f1b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..6db7fdc93be --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..4ef90b70573 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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 in '{0}' from version : '{1}' + + + ```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/Chaos.Management.brown/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..dce7214beda --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..041c97ea452 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..c0b0a35c689 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..fbea84e6a12 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..f99bf77f395 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..82016cb21cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..92b86955a28 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.Chaos.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.Chaos.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..724d345c924 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..0e101aa1d4b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/how-to.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/how-to.md new file mode 100644 index 00000000000..ceea203e91b --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.Chaos`. + +## Building `Az.Chaos` +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.Chaos` +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.Chaos` +To pack `Az.Chaos` 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.Chaos`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Chaos.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Chaos.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Chaos`. + - `-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.Chaos` 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/Chaos.Management.brown/target/internal/Az.Chaos.internal.psm1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/internal/Az.Chaos.internal.psm1 new file mode 100644 index 00000000000..9df529f9e29 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/internal/Az.Chaos.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Chaos.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Chaos.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/Chaos.Management.brown/target/internal/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/internal/README.md new file mode 100644 index 00000000000..cc8e54568ca --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.Chaos`. Instead, this sub-module is imported by the `..\custom\Az.Chaos.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.Chaos.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.Chaos`. diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/license.txt b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/pack-module.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/resources/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/run-module.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/run-module.ps1 new file mode 100644 index 00000000000..a66c1cf0f58 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/test-module.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/test-module.ps1 new file mode 100644 index 00000000000..d3f276b2676 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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.Chaos.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/Chaos.Management.brown/target/test/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/README.md new file mode 100644 index 00000000000..d28996846ef --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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: + - https://github.com/Azure/azure-rest-api-specs/blob/d55f30f41f04e712de101fc9c17a591ca410bfed/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/Chaos.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/Chaos.Management.brown/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/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/Chaos.Management.brown/targetType.models.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/targetType.models.tsp new file mode 100644 index 00000000000..85bd62d5f09 --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/targetType.models.tsp @@ -0,0 +1,64 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./experiment.models.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +/** + * Model that represents a Target Type resource. + */ +@subscriptionResource +@parentResource(SubscriptionLocationResource) +model TargetType + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = TargetType, + KeyName = "targetTypeName", + SegmentName = "targetTypes", + NamePattern = "^[a-zA-Z0-9_\\-\\.]+$" + >; +} + +/** + * Model that represents the base Target Type properties model. + */ +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "Read-only metadata resource." +model TargetTypeProperties { + /** + * Localized string of the display name. + */ + @visibility(Lifecycle.Read) + displayName?: string; + + /** + * Localized string of the description. + */ + @visibility(Lifecycle.Read) + description?: string; + + /** + * URL to retrieve JSON schema of the Target Type properties. + */ + @visibility(Lifecycle.Read) + @maxLength(2048) + propertiesSchema?: string; + + /** + * List of resource types this Target Type can extend. + */ + @visibility(Lifecycle.Read) + resourceTypes?: string[]; +} + +/** + * Model that represents a list of Target Type resources and a link for pagination. + */ +model TargetTypeListResult is Azure.Core.Page; diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/targetType.tsp b/tests-upgrade/tests-emitter/Chaos.Management.brown/targetType.tsp new file mode 100644 index 00000000000..742f07b3daf --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/targetType.tsp @@ -0,0 +1,42 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./targetType.models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Chaos; + +@armResourceOperations +interface TargetTypes { + /** + * Get a Target Type resources for given location. + */ + get is ArmResourceRead< + TargetType, + Azure.ResourceManager.Foundations.SubscriptionBaseParameters + >; + + /** + * Get a list of Target Type resources for given location. + */ + list is ArmResourceListByParent< + TargetType, + Azure.ResourceManager.Foundations.SubscriptionBaseParameters, + Parameters = { + /** + * String that sets the continuation token. + */ + @query("continuationToken") + continuationToken?: string; + }, + Response = TargetTypeListResult + >; +} + +@@doc(TargetType.name, "String that represents a Target Type resource name."); +@@doc(TargetType.properties, "The properties of the target type resource."); diff --git a/tests-upgrade/tests-emitter/Chaos.Management.brown/tspconfig.yaml b/tests-upgrade/tests-emitter/Chaos.Management.brown/tspconfig.yaml new file mode 100644 index 00000000000..e5791edac7e --- /dev/null +++ b/tests-upgrade/tests-emitter/Chaos.Management.brown/tspconfig.yaml @@ -0,0 +1,115 @@ +parameters: + "service-dir": + default: "sdk/chaos" +emit: + - "@azure-tools/typespec-autorest" +options: + "@azure-tools/typespec-autorest": + 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 + emitter-output-dir: "{project-root}/.." + output-file: "{azure-resource-provider-folder}/{service-name}/{version-status}/{version}/openapi.json" + omit-unreachable-types: true + use-read-only-status-schema: true + "@azure-tools/typespec-ts": + experimental-extensible-enums: true + package-dir: "arm-chaos" + flavor: azure + package-details: + name: "@azure/arm-chaos" + "@azure-tools/typespec-python": + package-dir: "azure-mgmt-chaos" + namespace: "azure.mgmt.chaos" + flavor: "azure" + generate-test: true + generate-sample: true + "@azure-tools/typespec-csharp": + flavor: azure + package-dir: "Azure.ResourceManager.Chaos" + clear-output-folder: true + model-namespace: false + namespace: "{package-dir}" + "@azure-tools/typespec-go": + service-dir: "sdk/resourcemanager/chaos" + package-dir: "armchaos" + module: "github.com/Azure/azure-sdk-for-go/{service-dir}/{package-dir}" + fix-const-stuttering: true + flavor: "azure" + generate-samples: true + generate-fakes: true + head-as-boolean: true + inject-spans: true + "@azure-tools/typespec-java": + package-dir: "azure-resourcemanager-chaos" + namespace: "com.azure.resourcemanager.chaos" + service-name: "Chaos" + flavor: "azure" + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "Chaos/Chaos.Autorest" + clear-output-folder: true + debug: true + azure: true + module-version: 0.1.0 + prefix: "Az" + subject-prefix: "Chaos" + service-name: Chaos + module-name: "{prefix}.{service-name}" + # output-folder: "{output-dir}" + emit-modeler-output: true + 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|Export)(?!.*?Expanded|ViaJsonString|ViaJsonFilePath) + remove: true + - where: + subject: MapConnection + variant: ^(Get)(?!.*?Expanded|ViaJsonString|ViaJsonFilePath) + remove: true + - where: + variant: ^CreateViaIdentity$|^CreateViaIdentityExpanded$ + remove: true + - where: + verb: Set + remove: true + # Remove four post operations since there are issues in tsp and response schema are not defined. + # - where: + # subject: MapConnection|MapDependencyView + # verb: Get + # remove: true + # - where: + # verb: Export + # remove: true + # - no-inline: + # - DiscoverySourceResourceProperties + # - model-cmdlet: + # - model-name: OffAzureDiscoverySourceResourceProperties + - where: + subject: OperationStatuses + remove: true + + - where: + verb: Invoke + set: + verb: Get + + - model-cmdlet: + - model-name: Selector + - model-name: Step + - model-name: Branch + - model-name: Action +linter: + extends: + - "@azure-tools/typespec-azure-rulesets/resource-manager" diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/IntegrationFabric.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/IntegrationFabric.tsp new file mode 100644 index 00000000000..7340123525f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/IntegrationFabric.tsp @@ -0,0 +1,61 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./ManagedGrafana.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Dashboard; +/** + * The integration fabric resource type. + */ +@parentResource(ManagedGrafana) +model IntegrationFabric + is Azure.ResourceManager.TrackedResource { + ...ResourceNameParameter< + Resource = IntegrationFabric, + KeyName = "integrationFabricName", + SegmentName = "integrationFabrics", + NamePattern = "^[a-zA-Z][a-z0-9A-Z-]{0,18}[a-z0-9A-Z]$" + >; +} + +@armResourceOperations +interface IntegrationFabrics { + get is ArmResourceRead; + + create is ArmResourceCreateOrReplaceAsync; + + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchAsync< + IntegrationFabric, + PatchModel = IntegrationFabricUpdateParameters, + LroHeaders = ArmAsyncOperationHeader & + Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + delete is ArmResourceDeleteWithoutOkAsync< + IntegrationFabric, + LroHeaders = ArmAsyncOperationHeader & + Azure.Core.Foundations.RetryAfterHeader + >; + + list is ArmResourceListByParent< + IntegrationFabric, + Response = ArmResponse + >; +} + +@@doc(IntegrationFabric.name, + "The integration fabric name of Azure Managed Grafana." +); +@@doc(IntegrationFabric.properties, ""); +@@doc(IntegrationFabrics.create::parameters.resource, ""); +@@doc(IntegrationFabrics.update::parameters.properties, ""); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedDashboard.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedDashboard.tsp new file mode 100644 index 00000000000..aa5dbf8cb73 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedDashboard.tsp @@ -0,0 +1,80 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Dashboard; +/** + * The managed dashboard resource type. + */ +model ManagedDashboard + is Azure.ResourceManager.TrackedResource { + ...ResourceNameParameter< + Resource = ManagedDashboard, + KeyName = "dashboardName", + SegmentName = "dashboards", + NamePattern = "^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$" + >; +} + +@armResourceOperations +interface ManagedDashboards { + /** + * Get the properties of a specific dashboard for grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Dashboards_Get") + get is ArmResourceRead; + + /** + * Create or update a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or update an existing dashboard. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Update a dashboard for Grafana resource. + */ + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchSync< + ManagedDashboard, + PatchModel = ManagedDashboardUpdateParameters + >; + + /** + * Delete a dashboard for Grafana resource. + */ + delete is ArmResourceDeleteSync; + + /** + * List all resources of dashboards under the specified resource group. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Dashboards_List") + list is ArmResourceListByParent< + ManagedDashboard, + Response = ArmResponse + >; + + /** + * List all resources of dashboards under the specified subscription. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Dashboards_ListBySubscription") + listBySubscription is ArmListBySubscription< + ManagedDashboard, + Response = ArmResponse + >; +} + +@@doc(ManagedDashboard.name, "The name of the Azure Managed Dashboard."); +@@doc(ManagedDashboard.properties, + "Properties specific to the managed dashboard resource." +); +@@doc(ManagedDashboards.create::parameters.resource, ""); +@@doc(ManagedDashboards.update::parameters.properties, ""); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedGrafana.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedGrafana.tsp new file mode 100644 index 00000000000..013ddf7be8c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedGrafana.tsp @@ -0,0 +1,151 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Dashboard; +/** + * The grafana resource type. + */ +model ManagedGrafana + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = ManagedGrafana, + KeyName = "workspaceName", + SegmentName = "grafana", + NamePattern = "^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$" + >; + + /** + * The Sku of the grafana resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + sku?: ResourceSku; + + /** Resource tags. */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + tags?: Record; + + /** The geo-location where the resource lives */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read, Lifecycle.Create) + location?: string; + + ...Azure.ResourceManager.ManagedServiceIdentityProperty; +} + +@armResourceOperations +interface ManagedGrafanas { + /** + * Get the properties of a specific workspace for Grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_Get") + get is ArmResourceRead; + + /** + * Create or update a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or update an existing grafana. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_Create") + create is ArmResourceCreateOrReplaceAsync; + + /** + * Update a workspace for Grafana resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/no-response-body" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @patch(#{ implicitOptionality: false }) + @operationId("Grafana_Update") + update is ArmCustomPatchAsync< + ManagedGrafana, + PatchModel = ManagedGrafanaUpdateParameters, + Response = ArmResponse | (ArmAcceptedLroResponse & + Azure.Core.Foundations.RetryAfterHeader> & { + @bodyRoot + _: ManagedGrafana; + }) + >; + + /** + * Delete a workspace for Grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-delete-operation-response-codes" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_Delete") + delete is ArmResourceDeleteWithoutOkAsync< + ManagedGrafana, + Response = ArmDeletedResponse | ArmDeleteAcceptedLroResponse | ArmDeletedNoContentResponse + >; + + /** + * List all resources of workspaces for Grafana under the specified resource group. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_ListByResourceGroup") + listByResourceGroup is ArmResourceListByParent< + ManagedGrafana, + Response = ArmResponse + >; + + /** + * List all resources of workspaces for Grafana under the specified subscription. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_List") + list is ArmListBySubscription< + ManagedGrafana, + Response = ArmResponse + >; + + /** + * Retrieve enterprise add-on details information + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_CheckEnterpriseDetails") + checkEnterpriseDetails is ArmResourceActionSync< + ManagedGrafana, + void, + ArmResponse + >; + + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("Grafana_FetchAvailablePlugins") + fetchAvailablePlugins is ArmResourceActionSync< + ManagedGrafana, + void, + ArmResponse + >; + + /** + * Refresh and sync managed private endpoints of a grafana resource to latest state. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @action("refreshManagedPrivateEndpoints") + @operationId("ManagedPrivateEndpoints_Refresh") + refresh is ArmResourceActionAsync< + ManagedGrafana, + void, + OkResponse, + LroHeaders = ArmAsyncOperationHeader & + Azure.Core.Foundations.RetryAfterHeader + >; +} + +@@doc(ManagedGrafana.name, "The workspace name of Azure Managed Grafana."); +@@doc(ManagedGrafana.properties, + "Properties specific to the grafana resource." +); +@@doc(ManagedGrafanas.create::parameters.resource, ""); +@@doc(ManagedGrafanas.update::parameters.properties, ""); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedPrivateEndpointModel.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedPrivateEndpointModel.tsp new file mode 100644 index 00000000000..e417d19808d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/ManagedPrivateEndpointModel.tsp @@ -0,0 +1,103 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./ManagedGrafana.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Dashboard; +/** + * The managed private endpoint resource type. + */ +@parentResource(ManagedGrafana) +model ManagedPrivateEndpointModel + is Azure.ResourceManager.TrackedResource { + ...ResourceNameParameter< + Resource = ManagedPrivateEndpointModel, + KeyName = "managedPrivateEndpointName", + SegmentName = "managedPrivateEndpoints", + NamePattern = "" + >; +} + +@armResourceOperations +interface ManagedPrivateEndpointModels { + /** + * Get a specific managed private endpoint of a grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("ManagedPrivateEndpoints_Get") + get is ArmResourceRead; + + /** + * Create or update a managed private endpoint for a grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @Azure.Core.useFinalStateVia("original-uri") + @operationId("ManagedPrivateEndpoints_Create") + create is ArmResourceCreateOrReplaceAsync< + ManagedPrivateEndpointModel, + Response = ArmResourceUpdatedResponse | ArmResourceCreatedResponse< + Resource = ManagedPrivateEndpointModel, + LroHeaders = ArmAsyncOperationHeader & + Azure.Core.Foundations.RetryAfterHeader + > + >; + + /** + * Update a managed private endpoint for an existing grafana resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/no-response-body" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @patch(#{ implicitOptionality: false }) + @operationId("ManagedPrivateEndpoints_Update") + update is ArmCustomPatchAsync< + ManagedPrivateEndpointModel, + PatchModel = ManagedPrivateEndpointUpdateParameters, + Response = ArmResponse | (ArmAcceptedLroResponse & + Azure.Core.Foundations.RetryAfterHeader> & { + @bodyRoot + _: ManagedPrivateEndpointModel; + }) + >; + + /** + * Delete a managed private endpoint for a grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-delete-operation-response-codes" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("ManagedPrivateEndpoints_Delete") + delete is ArmResourceDeleteWithoutOkAsync< + ManagedPrivateEndpointModel, + Response = ArmDeletedResponse | ArmDeleteAcceptedLroResponse | ArmDeletedNoContentResponse + >; + + /** + * List all managed private endpoints of a grafana resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @operationId("ManagedPrivateEndpoints_List") + list is ArmResourceListByParent< + ManagedPrivateEndpointModel, + Response = ArmResponse + >; +} + +@@doc(ManagedPrivateEndpointModel.name, + "The managed private endpoint name of Azure Managed Grafana." +); +@@doc(ManagedPrivateEndpointModel.properties, "Resource properties."); +@@doc(ManagedPrivateEndpointModels.create::parameters.resource, + "The managed private endpoint to be created or updated." +); +@@doc(ManagedPrivateEndpointModels.update::parameters.properties, + "Properties that can be updated to an existing managed private endpoint." +); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/PrivateEndpointConnection.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/PrivateEndpointConnection.tsp new file mode 100644 index 00000000000..edf2a77568f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/PrivateEndpointConnection.tsp @@ -0,0 +1,98 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./ManagedGrafana.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Dashboard; +/** + * The Private Endpoint Connection resource. + */ +@parentResource(ManagedGrafana) +model PrivateEndpointConnection + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PrivateEndpointConnection, + KeyName = "privateEndpointConnectionName", + SegmentName = "privateEndpointConnections", + NamePattern = "" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-legacy-usage" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +@armResourceOperations +interface PrivateEndpointConnectionsOps + extends Azure.ResourceManager.Legacy.LegacyOperations< + { + ...ApiVersionParameter, + ...SubscriptionIdParameter, + ...ResourceGroupParameter, + ...Azure.ResourceManager.Legacy.Provider, + + /** + * The workspace name of Azure Managed Grafana. + */ + @path + @segment("grafana") + @pattern("^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$") + workspaceName: string, + }, + { + /** + * The private endpoint connection name of Azure Managed Grafana. + */ + @path + @segment("privateEndpointConnections") + privateEndpointConnectionName: string, + }, + ErrorResponse + > {} + +@armResourceOperations +interface PrivateEndpointConnections { + /** + * Get private endpoint connections. + */ + get is ArmResourceRead; + + /** + * Manual approve private endpoint connection + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-put-operation-response-codes" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + approve is PrivateEndpointConnectionsOps.CreateOrUpdateAsync< + PrivateEndpointConnection, + Response = ArmResourceCreatedResponse< + Resource = PrivateEndpointConnection, + LroHeaders = ArmAsyncOperationHeader & + Azure.Core.Foundations.RetryAfterHeader + >, + OptionalRequestBody = true + >; + + /** + * Delete private endpoint connection + */ + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + delete is ArmResourceDeleteWithoutOkAsync< + PrivateEndpointConnection, + LroHeaders = ArmAsyncOperationHeader & + Azure.Core.Foundations.RetryAfterHeader + >; + + /** + * Get private endpoint connection + */ + list is ArmResourceListByParent; +} + +@@doc(PrivateEndpointConnection.name, + "The private endpoint connection name of Azure Managed Grafana." +); +@@doc(PrivateEndpointConnection.properties, "Resource properties."); +@@doc(PrivateEndpointConnections.approve::parameters.resource, ""); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/PrivateLinkResource.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/PrivateLinkResource.tsp new file mode 100644 index 00000000000..0bbabe88e2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/PrivateLinkResource.tsp @@ -0,0 +1,42 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./ManagedGrafana.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.Dashboard; +/** + * A private link resource + */ +@parentResource(ManagedGrafana) +model PrivateLinkResource + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PrivateLinkResource, + KeyName = "privateLinkResourceName", + SegmentName = "privateLinkResources", + NamePattern = "" + >; +} + +@armResourceOperations +interface PrivateLinkResources { + /** + * Get specific private link resource information for this grafana resource + */ + get is ArmResourceRead; + + /** + * List all private link resources information for this grafana resource + */ + list is ArmResourceListByParent; +} + +@@doc(PrivateLinkResource.name, ""); +@@doc(PrivateLinkResource.properties, "Resource properties."); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/back-compatible.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/back-compatible.tsp new file mode 100644 index 00000000000..199ca176326 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/back-compatible.tsp @@ -0,0 +1,83 @@ +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; +using Microsoft.Dashboard; +using Azure.Core; + +@@clientName(ManagedGrafanas.create::parameters.resource, + "requestBodyParameters" +); +@@clientName(ManagedGrafanas.update::parameters.properties, + "requestBodyParameters" +); + +#suppress "deprecated" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +@@flattenProperty(PrivateEndpointConnection.properties); + +#suppress "deprecated" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +@@flattenProperty(PrivateLinkResource.properties); + +@@clientName(ManagedPrivateEndpointModels.create::parameters.resource, + "requestBodyParameters" +); +@@clientName(ManagedPrivateEndpointModels.update::parameters.properties, + "requestBodyParameters" +); +#suppress "deprecated" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +@@flattenProperty(ManagedPrivateEndpointModel.properties); + +@@clientName(IntegrationFabrics.create::parameters.resource, + "requestBodyParameters" +); +@@clientName(IntegrationFabrics.update::parameters.properties, + "requestBodyParameters" +); + +@@clientName(ManagedDashboards.create::parameters.resource, + "requestBodyParameters" +); +@@clientName(ManagedDashboards.update::parameters.properties, + "requestBodyParameters" +); +@@clientName(PrivateEndpointConnections.approve::parameters.resource, "body"); +#suppress "deprecated" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +@@flattenProperty(ManagedDashboard.properties); +@@alternateType(ManagedPrivateEndpointModelProperties.privateLinkResourceId, + armResourceIdentifier +); +@@alternateType(ManagedPrivateEndpointModelProperties.privateLinkServiceUrl, + url +); +@@alternateType(AzureMonitorWorkspaceIntegration.azureMonitorWorkspaceResourceId, + armResourceIdentifier +); + +@@clientLocation(ManagedGrafanas.get, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.create, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.update, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.delete, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.listByResourceGroup, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.list, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.checkEnterpriseDetails, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.fetchAvailablePlugins, "Grafana", "!csharp"); +@@clientLocation(ManagedGrafanas.refresh, "ManagedPrivateEndpoints", "!csharp"); +@@clientLocation(ManagedPrivateEndpointModels.get, + "ManagedPrivateEndpoints", + "!csharp" +); +@@clientLocation(ManagedPrivateEndpointModels.create, + "ManagedPrivateEndpoints", + "!csharp" +); +@@clientLocation(ManagedPrivateEndpointModels.update, + "ManagedPrivateEndpoints", + "!csharp" +); +@@clientLocation(ManagedPrivateEndpointModels.delete, + "ManagedPrivateEndpoints", + "!csharp" +); +@@clientLocation(ManagedPrivateEndpointModels.list, + "ManagedPrivateEndpoints", + "!csharp" +); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/client.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/client.tsp new file mode 100644 index 00000000000..6eed3bd2f8b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/client.tsp @@ -0,0 +1,77 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; +using Microsoft.Dashboard; + +@@clientName(PrivateEndpointConnectionProperties.privateLinkServiceConnectionState, + "ConnectionState", + "csharp" +); +@@clientName(ManagedGrafanas.refresh, + "RefreshManagedPrivateEndpoint", + "csharp" +); +@@clientName(PrivateLinkResource, "GrafanaPrivateLinkResource", "csharp"); +@@clientName(ResourceSku, "ManagedGrafanaSku", "csharp"); +@@clientName(ProvisioningState, "GrafanaProvisioningState", "csharp"); +@@clientName(PublicNetworkAccess, "GrafanaPublicNetworkAccess", "csharp"); +@@clientName(ZoneRedundancy, "GrafanaZoneRedundancy", "csharp"); +@@clientName(ApiKey, "GrafanaApiKey", "csharp"); +@@clientName(GrafanaIntegrations.azureMonitorWorkspaceIntegrations, + "MonitorWorkspaceIntegrations", + "csharp" +); +@@clientName(AzureMonitorWorkspaceIntegration, + "MonitorWorkspaceIntegration", + "csharp" +); +@@clientName(AzureMonitorWorkspaceIntegration.azureMonitorWorkspaceResourceId, + "MonitorWorkspaceResourceId", + "csharp" +); +@@clientName(ManagedGrafanaPropertiesUpdateParameters, + "ManagedGrafanaPatchProperties", + "csharp" +); +@@clientName(IntegrationFabric, "GrafanaIntegrationFabric", "csharp"); +@@clientName(IntegrationFabricProperties, + "GrafanaIntegrationFabricProperties", + "csharp" +); +@@clientName(Snapshots, "GrafanaSnapshotsSettings", "csharp"); +@@clientName(Snapshots.externalEnabled, "IsExternalEnabled", "csharp"); +@@clientName(Security, "GrafanaSecuritySettings", "csharp"); +@@clientName(Security.csrfAlwaysCheck, "IsCsrfAlwaysCheckEnabled", "csharp"); +@@clientName(UnifiedAlertingScreenshots.captureEnabled, + "IsCaptureEnabled", + "csharp" +); +@@clientName(Smtp, "GrafanaSmtpSettings", "csharp"); +@@clientName(Smtp.enabled, "IsEnabled", "csharp"); +@@clientName(Users, "GrafanaUserSettings", "csharp"); +@@clientName(StartTLSPolicy, "GrafanaStartTlsPolicy", "csharp"); +@@clientName(StartTLSPolicy.OpportunisticStartTLS, + "OpportunisticStartTls", + "csharp" +); +@@clientName(StartTLSPolicy.MandatoryStartTLS, "MandatoryStartTls", "csharp"); +@@clientName(StartTLSPolicy.NoStartTLS, "NoStartTls", "csharp"); + +@@clientName(DeterministicOutboundIP, "DeterministicOutboundIp", "java"); +@@clientName(StartTLSPolicy, "StartTlsPolicy", "java"); +@@clientName(ManagedGrafanaProperties.deterministicOutboundIP, + "deterministicOutboundIp", + "java" +); +@@clientName(ManagedGrafanaPropertiesUpdateParameters.deterministicOutboundIP, + "deterministicOutboundIp", + "java" +); +@@clientName(ManagedPrivateEndpointModelProperties.privateLinkServicePrivateIP, + "privateLinkServicePrivateIp", + "java" +); +@@clientName(Smtp.startTLSPolicy, "startTlsPolicy", "java"); +@@clientName(Microsoft.Dashboard, "DashboardManagementClient", "javascript"); +@@clientName(Microsoft.Dashboard, "DashboardManagementClient", "python"); diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/main.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/main.tsp new file mode 100644 index 00000000000..d13e7419ffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/main.tsp @@ -0,0 +1,50 @@ +/** + * PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS + * Generated by package: @autorest/openapi-to-typespec + * Parameters used: + * isFullCompatible: true + * guessResourceKey: false + * Version: 0.11.0 + * Date: 2025-05-21T07:11:29.261Z + */ +import "@typespec/rest"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./models.tsp"; +import "./back-compatible.tsp"; +import "./ManagedGrafana.tsp"; +import "./PrivateEndpointConnection.tsp"; +import "./PrivateLinkResource.tsp"; +import "./ManagedPrivateEndpointModel.tsp"; +import "./IntegrationFabric.tsp"; +import "./ManagedDashboard.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager.Foundations; +using Azure.Core; +using Azure.ResourceManager; +using TypeSpec.Versioning; +/** + * The Microsoft.Dashboard Rest API spec. + */ +@armProviderNamespace +@service(#{ title: "Microsoft.Dashboard" }) +@versioned(Versions) +@armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v3) +namespace Microsoft.Dashboard; + +/** + * The available API versions. + */ +enum Versions { + /** + * The 2024-11-01-preview API version. + */ + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(Azure.Core.Versions.v1_0_Preview_1) + v2024_11_01_preview: "2024-11-01-preview", +} + +interface Operations extends Azure.ResourceManager.Operations {} diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/models.tsp b/tests-upgrade/tests-emitter/Dashboard.Management.brown/models.tsp new file mode 100644 index 00000000000..5a90f933625 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/models.tsp @@ -0,0 +1,905 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; + +namespace Microsoft.Dashboard; + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +union ProvisioningState { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Accepted: "Accepted", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Creating: "Creating", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Updating: "Updating", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Deleting: "Deleting", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Succeeded: "Succeeded", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Failed: "Failed", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Canceled: "Canceled", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Deleted: "Deleted", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + NotSpecified: "NotSpecified", +} + +/** + * Indicate the state for enable or disable traffic over the public interface. + */ +union PublicNetworkAccess { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Enabled: "Enabled", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Disabled: "Disabled", +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +union ZoneRedundancy { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Disabled: "Disabled", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Enabled: "Enabled", +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +union ApiKey { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Disabled: "Disabled", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Enabled: "Enabled", +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +union DeterministicOutboundIP { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Disabled: "Disabled", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Enabled: "Enabled", +} + +/** + * The private endpoint connection status. + */ +union PrivateEndpointServiceConnectionStatus { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Pending: "Pending", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Approved: "Approved", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Rejected: "Rejected", +} + +/** + * Scope for dns deterministic name hash calculation + */ +union AutoGeneratedDomainNameLabelScope { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + TenantReuse: "TenantReuse", +} + +/** + * The AutoRenew setting of the Enterprise subscription + */ +union MarketplaceAutoRenew { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Disabled: "Disabled", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Enabled: "Enabled", +} + +/** + * The StartTLSPolicy setting of the SMTP configuration + * https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + */ +union StartTLSPolicy { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + OpportunisticStartTLS: "OpportunisticStartTLS", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + MandatoryStartTLS: "MandatoryStartTLS", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + NoStartTLS: "NoStartTLS", +} + +/** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + */ +union ManagedServiceIdentityType { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + None: "None", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + SystemAssigned: "SystemAssigned", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + UserAssigned: "UserAssigned", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + `SystemAssigned,UserAssigned`: "SystemAssigned,UserAssigned", +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +union AvailablePromotion { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + None: "None", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + FreeTrial: "FreeTrial", +} + +/** + * The approval/rejection status of managed private endpoint connection. + */ +union ManagedPrivateEndpointConnectionStatus { + string, + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Pending: "Pending", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Approved: "Approved", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Rejected: "Rejected", + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + Disconnected: "Disconnected", +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +model ManagedGrafanaListResponse is Azure.Core.Page; + +/** + * Properties specific to the grafana resource. + */ +model ManagedGrafanaProperties { + /** + * Provisioning state of the resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * The Grafana software version. + */ + @visibility(Lifecycle.Read) + grafanaVersion?: string; + + /** + * The endpoint of the Grafana instance. + */ + @visibility(Lifecycle.Read) + endpoint?: string; + + /** + * Indicate the state for enable or disable traffic over the public interface. + */ + publicNetworkAccess?: PublicNetworkAccess = PublicNetworkAccess.Enabled; + + /** + * The zone redundancy setting of the Grafana instance. + */ + zoneRedundancy?: ZoneRedundancy = ZoneRedundancy.Disabled; + + /** + * The api key setting of the Grafana instance. + */ + apiKey?: ApiKey = ApiKey.Disabled; + + /** + * Whether a Grafana instance uses deterministic outbound IPs. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + deterministicOutboundIP?: DeterministicOutboundIP = DeterministicOutboundIP.Disabled; + + /** + * List of outbound IPs if deterministicOutboundIP is enabled. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read) + outboundIPs?: string[]; + + /** + * The private endpoint connections of the Grafana instance. + */ + @visibility(Lifecycle.Read) + privateEndpointConnections?: PrivateEndpointConnection[]; + + /** + * Scope for dns deterministic name hash calculation. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + autoGeneratedDomainNameLabelScope?: AutoGeneratedDomainNameLabelScope; + + /** + * GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, alerting defaults) for common monitoring scenarios. + */ + grafanaIntegrations?: GrafanaIntegrations; + + /** + * Enterprise settings of a Grafana instance + */ + enterpriseConfigurations?: EnterpriseConfigurations; + + /** + * Server configurations of a Grafana instance + */ + grafanaConfigurations?: GrafanaConfigurations; + + /** + * Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + grafanaPlugins?: Record; + + /** + * The major Grafana software version to target. + */ + grafanaMajorVersion?: string; +} + +/** + * Properties of the PrivateEndpointConnectProperties. + */ +model PrivateEndpointConnectionProperties { + /** + * The resource of private end point. + */ + privateEndpoint?: Azure.ResourceManager.CommonTypes.PrivateEndpoint; + + /** + * A collection of information about the state of the connection between service consumer and provider. + */ + privateLinkServiceConnectionState: Azure.ResourceManager.CommonTypes.PrivateLinkServiceConnectionState; + + /** + * The private endpoint connection group ids. + */ + groupIds?: string[]; + + /** + * The provisioning state of the private endpoint connection resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-provisioning-state" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read) + provisioningState?: Azure.ResourceManager.CommonTypes.PrivateEndpointConnectionProvisioningState; +} + +/** + * Common fields that are returned in the response for all Azure Resource Manager resources + */ +model Resource { + /** + * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * The name of the resource + */ + @visibility(Lifecycle.Read) + name?: string; + + /** + * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + */ + @visibility(Lifecycle.Read) + type?: string; + + /** + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + @visibility(Lifecycle.Read) + systemData?: SystemData; +} + +/** + * GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, alerting defaults) for common monitoring scenarios. + */ +model GrafanaIntegrations { + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @OpenAPI.extension("x-ms-identifiers", #[]) + azureMonitorWorkspaceIntegrations?: AzureMonitorWorkspaceIntegration[]; +} + +/** + * Integrations for Azure Monitor Workspace. + */ +model AzureMonitorWorkspaceIntegration { + /** + * The resource Id of the connected Azure Monitor Workspace. + */ + azureMonitorWorkspaceResourceId?: string; +} + +/** + * Enterprise settings of a Grafana instance + */ +model EnterpriseConfigurations { + /** + * The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + */ + marketplacePlanId?: string; + + /** + * The AutoRenew setting of the Enterprise subscription + */ + marketplaceAutoRenew?: MarketplaceAutoRenew; +} + +/** + * Server configurations of a Grafana instance + */ +model GrafanaConfigurations { + /** + * Email server settings. + * https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + */ + smtp?: Smtp; + + /** + * Grafana Snapshots settings + */ + snapshots?: Snapshots; + + /** + * Grafana users settings + */ + users?: Users; + + /** + * Grafana security settings + */ + security?: Security; + + /** + * Grafana Unified Alerting Screenshots settings + */ + unifiedAlertingScreenshots?: UnifiedAlertingScreenshots; +} + +/** + * Email server settings. + * https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + */ +model Smtp { + /** + * Enable this to allow Grafana to send email. Default is false + */ + enabled?: boolean = false; + + /** + * SMTP server hostname with port, e.g. test.email.net:587 + */ + host?: string; + + /** + * User of SMTP auth + */ + user?: string; + + /** + * Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + */ + @secret + password?: string; + + /** + * Address used when sending out emails + * https://pkg.go.dev/net/mail#Address + */ + fromAddress?: string; + + /** + * Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + * https://pkg.go.dev/net/mail#Address + */ + fromName?: string; + + /** + * The StartTLSPolicy setting of the SMTP configuration + * https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + startTLSPolicy?: StartTLSPolicy; + + /** + * Verify SSL for SMTP server. Default is false + * https://pkg.go.dev/crypto/tls#Config + */ + skipVerify?: boolean; +} + +/** + * Grafana Snapshots settings + */ +model Snapshots { + /** + * Set to false to disable external snapshot publish endpoint + */ + externalEnabled?: boolean; +} + +/** + * Grafana users settings + */ +model Users { + /** + * Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes. + */ + viewersCanEdit?: boolean; + + /** + * Set to true so editors can administrate dashboards, folders and teams they create. + */ + editorsCanAdmin?: boolean; +} + +/** + * Grafana security settings + */ +model Security { + /** + * Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + */ + csrfAlwaysCheck?: boolean; +} + +/** + * Grafana Unified Alerting Screenshots settings + */ +model UnifiedAlertingScreenshots { + /** + * Set to false to disable capture screenshot in Unified Alert due to performance issue. + */ + captureEnabled?: boolean; +} + +/** + * Plugin of Grafana + */ +model GrafanaPlugin { + /** + * Grafana plugin id + */ + @visibility(Lifecycle.Read) + pluginId?: string; +} + +/** + * Managed service identity (system assigned and/or user assigned identities) + */ +model ManagedServiceIdentity { + /** + * The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + */ + #suppress "@azure-tools/typespec-azure-core/no-format" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read) + @format("uuid") + principalId?: string; + + /** + * The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + */ + #suppress "@azure-tools/typespec-azure-core/no-format" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read) + @format("uuid") + tenantId?: string; + + /** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + */ + type: ManagedServiceIdentityType; + + /** + * The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. The dictionary values can be empty objects ({}) in requests. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + userAssignedIdentities?: Record; +} + +/** + * The parameters for a PATCH request to a grafana resource. + */ +model ManagedGrafanaUpdateParameters { + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + sku?: ResourceSku; + + /** + * The managed identity of the grafana resource. + */ + identity?: Azure.ResourceManager.Foundations.ManagedServiceIdentity; + + /** + * The new tags of the grafana resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + tags?: Record; + + /** + * Properties specific to the managed grafana resource. + */ + properties?: ManagedGrafanaPropertiesUpdateParameters; +} + +/** + * The properties parameters for a PATCH request to a grafana resource. + */ +model ManagedGrafanaPropertiesUpdateParameters { + /** + * The zone redundancy setting of the Grafana instance. + */ + zoneRedundancy?: ZoneRedundancy = ZoneRedundancy.Disabled; + + /** + * The api key setting of the Grafana instance. + */ + apiKey?: ApiKey = ApiKey.Disabled; + + /** + * Whether a Grafana instance uses deterministic outbound IPs. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + deterministicOutboundIP?: DeterministicOutboundIP = DeterministicOutboundIP.Disabled; + + /** + * Indicate the state for enable or disable traffic over the public interface. + */ + publicNetworkAccess?: PublicNetworkAccess = PublicNetworkAccess.Enabled; + + /** + * GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, alerting defaults) for common monitoring scenarios. + */ + grafanaIntegrations?: GrafanaIntegrations; + + /** + * Enterprise settings of a Grafana instance + */ + enterpriseConfigurations?: EnterpriseConfigurations; + + /** + * Server configurations of a Grafana instance + */ + grafanaConfigurations?: GrafanaConfigurations; + + /** + * Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given plugin id will be removed. Otherwise, given plugin will be installed. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + grafanaPlugins?: Record; + + /** + * The major Grafana software version to target. + */ + grafanaMajorVersion?: string; +} + +/** + * Properties of a private link resource. + */ +model PrivateLinkResourceProperties { + /** + * Provisioning state of the resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * The private link resource group id. + */ + @visibility(Lifecycle.Read) + groupId?: string; + + /** + * The private link resource required member names. + */ + @visibility(Lifecycle.Read) + requiredMembers?: string[]; + + /** + * The private link resource Private link DNS zone name. + */ + requiredZoneNames?: string[]; +} + +/** + * Enterprise details of a Grafana instance + */ +model EnterpriseDetails { + /** + * SaaS subscription details of a Grafana instance + */ + saasSubscriptionDetails?: SaasSubscriptionDetails; + + /** + * The allocation details of the per subscription free trial slot of the subscription. + */ + marketplaceTrialQuota?: MarketplaceTrialQuota; +} + +/** + * SaaS subscription details of a Grafana instance + */ +model SaasSubscriptionDetails { + /** + * The plan Id of the SaaS subscription. + */ + planId?: string; + + /** + * The offer Id of the SaaS subscription. + */ + offerId?: string; + + /** + * The publisher Id of the SaaS subscription. + */ + publisherId?: string; + + /** + * The billing term of the SaaS Subscription. + */ + term?: SubscriptionTerm; +} + +/** + * The current billing term of the SaaS Subscription. + */ +model SubscriptionTerm { + /** + * The unit of the billing term. + */ + termUnit?: string; + + /** + * The date and time in UTC of when the billing term starts. + */ + startDate?: utcDateTime; + + /** + * The date and time in UTC of when the billing term ends. + */ + endDate?: utcDateTime; +} + +/** + * The allocation details of the per subscription free trial slot of the subscription. + */ +model MarketplaceTrialQuota { + /** + * Available enterprise promotion for the subscription + */ + availablePromotion?: AvailablePromotion = AvailablePromotion.None; + + /** + * Resource Id of the Grafana resource which is doing the trial. + */ + grafanaResourceId?: Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.Dashboard/grafana"; + } + ]>; + + /** + * The date and time in UTC of when the trial starts. + */ + trialStartAt?: utcDateTime; + + /** + * The date and time in UTC of when the trial ends. + */ + trialEndAt?: utcDateTime; +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +model GrafanaAvailablePluginListResponse { + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @OpenAPI.extension("x-ms-identifiers", #["pluginId"]) + value?: GrafanaAvailablePlugin[]; + + #suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + nextLink?: string; +} + +/** + * Available plugins of grafana + */ +model GrafanaAvailablePlugin { + /** + * Grafana plugin id + */ + @visibility(Lifecycle.Read) + pluginId?: string; + + /** + * Grafana plugin display name + */ + @visibility(Lifecycle.Read) + name?: string; +} + +/** + * The list of managed private endpoints of a grafana resource + */ +model ManagedPrivateEndpointModelListResponse + is Azure.Core.Page; + +/** + * Properties specific to the managed private endpoint. + */ +model ManagedPrivateEndpointModelProperties { + /** + * Provisioning state of the resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * The ARM resource ID of the resource for which the managed private endpoint is pointing to. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + privateLinkResourceId?: string; + + /** + * The region of the resource to which the managed private endpoint is pointing to. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + privateLinkResourceRegion?: string; + + /** + * The group Ids of the managed private endpoint. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + groupIds?: string[]; + + /** + * User input request message of the managed private endpoint. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + requestMessage?: string; + + /** + * The state of managed private endpoint connection. + */ + @visibility(Lifecycle.Read) + connectionState?: ManagedPrivateEndpointConnectionState; + + /** + * The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration page without the protocol and port. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + privateLinkServiceUrl?: string; + + /** + * The private IP of private endpoint after approval. This property is empty before connection is approved. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + @visibility(Lifecycle.Read) + privateLinkServicePrivateIP?: string; +} + +/** + * The state of managed private endpoint connection. + */ +model ManagedPrivateEndpointConnectionState { + /** + * The approval/rejection status of managed private endpoint connection. + */ + @visibility(Lifecycle.Read) + status?: ManagedPrivateEndpointConnectionStatus; + + /** + * Gets or sets the reason for approval/rejection of the connection. + */ + @visibility(Lifecycle.Read) + description?: string; +} + +/** + * The parameters for a PATCH request to a managed private endpoint. + */ +model ManagedPrivateEndpointUpdateParameters { + /** + * The new tags of the managed private endpoint. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + tags?: Record; +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +model IntegrationFabricListResponse is Azure.Core.Page; + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +model IntegrationFabricProperties { + /** + * Provisioning state of the resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + */ + targetResourceId?: Azure.Core.armResourceIdentifier; + + /** + * The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, an Azure Data Explorer cluster, etc. + */ + dataSourceResourceId?: Azure.Core.armResourceIdentifier; + + /** + * A list of integration scenarios covered by this integration fabric + */ + scenarios?: string[]; +} + +/** + * The parameters for a PATCH request to a Integration Fabric resource. + */ +model IntegrationFabricUpdateParameters { + /** + * The new tags of the Integration Fabric resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + tags?: Record; + + /** + * The new properties of this Integration Fabric resource + */ + properties?: IntegrationFabricPropertiesUpdateParameters; +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +model IntegrationFabricPropertiesUpdateParameters { + /** + * The new integration scenarios covered by this integration fabric. + */ + scenarios?: string[]; +} + +#suppress "@azure-tools/typespec-azure-core/documentation-required" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" +model ManagedDashboardListResponse is Azure.Core.Page; + +/** + * Properties specific to the grafana resource. + */ +model ManagedDashboardProperties { + /** + * Provisioning state of the resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * The parameters for a PATCH request to a managed dashboard resource. + */ +model ManagedDashboardUpdateParameters { + /** + * The new tags of the managed dashboard resource. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "FIXME: Update justification, follow aka.ms/tsp/conversion-fix for details" + tags?: Record; +} +/** + * Represents the SKU of a resource. + */ +model ResourceSku { + /** + * The name of the SKU. + */ + name: string; +} diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/.gitattributes b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.csproj b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.csproj new file mode 100644 index 00000000000..b90e14835d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.Dashboard.private + false + Microsoft.Azure.PowerShell.Cmdlets.Dashboard + true + false + ./bin + $(OutputPath) + Az.Dashboard.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/Dashboard.Management.brown/target/Az.Dashboard.nuspec b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.nuspec new file mode 100644 index 00000000000..e3c55b28948 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.nuspec @@ -0,0 +1,32 @@ + + + + Az.Dashboard + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: Dashboard cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule Dashboard + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.psm1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.psm1 new file mode 100644 index 00000000000..86991807b79 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Az.Dashboard.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.Dashboard.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Properties/AssemblyInfo.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..4a67bc02d59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// 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. + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: System.Reflection.AssemblyCompanyAttribute("Microsoft")] +[assembly: System.Reflection.AssemblyCopyrightAttribute("Copyright © Microsoft")] +[assembly: System.Reflection.AssemblyProductAttribute("Microsoft Azure PowerShell")] +[assembly: System.Reflection.AssemblyTitleAttribute("Microsoft Azure PowerShell - MicrosoftDashboard")] +[assembly: System.Reflection.AssemblyFileVersionAttribute("0.1.0.0")] +[assembly: System.Reflection.AssemblyVersionAttribute("0.1.0.0")] +[assembly: System.Runtime.InteropServices.ComVisibleAttribute(false)] +[assembly: System.CLSCompliantAttribute(false)] \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/README.md new file mode 100644 index 00000000000..da20d2acfa9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/README.md @@ -0,0 +1,24 @@ + +# Az.Dashboard +This directory contains the PowerShell module for the Dashboard 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.Dashboard`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/build-module.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/build-module.ps1 new file mode 100644 index 00000000000..90526a1d168 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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 -Force -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 -Force -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.Dashboard.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.Dashboard.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 -Force +} +$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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $internalFolder + +$psd1 = Join-Path $PSScriptRoot './Az.Dashboard.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.Dashboard' +$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: Dashboard cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue -Force + } + $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.Dashboard.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 '../../../tools/BuildScripts/AdaptAutorestModule.ps1' + $afterBuildTasksArgs = ConvertFrom-Json '{"SubModuleName":"Az.Dashboard","ModuleRootName":"$(root-module-name)"}' -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/Dashboard.Management.brown/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..80669c4da3c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/create-model-cmdlets.ps1 @@ -0,0 +1,263 @@ +# ---------------------------------------------------------------------------------- +# 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.Dashboard' + } + $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}" + $Prefix = 'Az' + # remove duplicated module name + if ($ObjectType.StartsWith('Dashboard')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'Dashboard' + } + $OutputPath = Join-Path -ChildPath "New-${Prefix}${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] + 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-${Prefix}${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} { + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ModelCmdletAttribute()] + [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/Dashboard.Management.brown/target/custom/Az.Dashboard.custom.psm1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/custom/Az.Dashboard.custom.psm1 new file mode 100644 index 00000000000..c31b0fb6cc2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/custom/Az.Dashboard.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Dashboard.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.Dashboard.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/Dashboard.Management.brown/target/custom/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/custom/README.md new file mode 100644 index 00000000000..842936a87dc --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.Dashboard` 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.Dashboard.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.Dashboard` 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.Dashboard.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.Dashboard.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.Dashboard`. 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.Dashboard.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.Dashboard.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.Dashboard`. +- `Microsoft.Azure.PowerShell.Cmdlets.Dashboard.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.Dashboard`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/docs/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/docs/README.md new file mode 100644 index 00000000000..3f216e137df --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Dashboard` 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.Dashboard` 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/Dashboard.Management.brown/target/examples/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/export-surface.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/export-surface.ps1 new file mode 100644 index 00000000000..dafe3d95cb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.Dashboard' +$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/Dashboard.Management.brown/target/exports/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/exports/README.md new file mode 100644 index 00000000000..58f6f2f1205 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.Dashboard`. No other cmdlets in this repository are directly exported. What that means is the `Az.Dashboard` 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.Dashboard.private.dll`) and from the `..\custom\Az.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generate-help.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generate-help.ps1 new file mode 100644 index 00000000000..884c91f1dd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Dashboard.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.Dashboard.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..348377bc64f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard' +$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.Dashboard.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/Dashboard.Management.brown/target/generated/Module.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/Module.cs new file mode 100644 index 00000000000..b63c8b70bcb --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard 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.Dashboard.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.Dashboard"; + + /// 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.Dashboard"; + + /// 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.Dashboard.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.Dashboard.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.Dashboard.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.MicrosoftDashboard(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/MicrosoftDashboard.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/MicrosoftDashboard.cs new file mode 100644 index 00000000000..3e510671ad2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/MicrosoftDashboard.cs @@ -0,0 +1,12702 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Low-level API implementation for the Microsoft.Dashboard service. + /// The Microsoft.Dashboard Rest API spec. + /// + public partial class MicrosoftDashboard + { + + /// Get the properties of a specific dashboard for grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsGet(string subscriptionId, string resourceGroupName, string dashboardName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DashboardsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get the properties of a specific dashboard for grafana 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsGetViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DashboardsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get the properties of a specific dashboard for grafana resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DashboardsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get the properties of a specific dashboard for grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsGetWithResult(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DashboardsGetWithResult_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.Dashboard.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 DashboardsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 DashboardsGet_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The name of the Azure Managed Dashboard. + /// 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 DashboardsGet_Validate(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(dashboardName),dashboardName); + await eventListener.AssertRegEx(nameof(dashboardName), dashboardName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// List all resources of dashboards under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsList(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DashboardsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all resources of dashboards under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DashboardsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all resources of dashboards under the specified subscription. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListBySubscriptionViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Dashboard/dashboards$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/dashboards'"); + } + + // 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.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DashboardsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all resources of dashboards under the specified subscription. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Dashboard/dashboards$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/dashboards'"); + } + + // 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.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DashboardsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// List all resources of dashboards under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DashboardsListBySubscriptionWithResult_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.Dashboard.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 DashboardsListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 DashboardsListBySubscription_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 DashboardsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + } + } + + /// List all resources of dashboards under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards$", 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.Dashboard/dashboards'"); + } + + // 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.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DashboardsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all resources of dashboards under the specified resource group. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards$", 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.Dashboard/dashboards'"); + } + + // 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.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DashboardsListWithResult_Call (request, eventListener,sender); + } + } + + /// List all resources of dashboards under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DashboardsListWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DashboardsListWithResult_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.Dashboard.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 DashboardsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 DashboardsList_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 DashboardsList_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + } + } + + /// Retrieve enterprise add-on details information + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaCheckEnterpriseDetails(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/checkEnterpriseDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaCheckEnterpriseDetails_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Retrieve enterprise add-on details information + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaCheckEnterpriseDetailsViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/checkEnterpriseDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaCheckEnterpriseDetails_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Retrieve enterprise add-on details information + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaCheckEnterpriseDetailsViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/checkEnterpriseDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaCheckEnterpriseDetailsWithResult_Call (request, eventListener,sender); + } + } + + /// Retrieve enterprise add-on details information + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaCheckEnterpriseDetailsWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/checkEnterpriseDetails" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaCheckEnterpriseDetailsWithResult_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.Dashboard.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 GrafanaCheckEnterpriseDetailsWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseDetails.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaCheckEnterpriseDetails_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseDetails.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 GrafanaCheckEnterpriseDetails_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The grafana resource type. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaCreate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// + /// The grafana resource type. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// + /// The grafana resource type. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// Json string supplied to the GrafanaCreate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaCreateViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// Json string supplied to the GrafanaCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The grafana resource type. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaCreateWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaCreateWithResult_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.Dashboard.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 GrafanaCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaCreate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The grafana resource type. + /// 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 GrafanaCreate_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaDelete(string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a workspace for Grafana resource. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 GrafanaDelete_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// A synchronous resource action. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaFetchAvailablePlugins(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/fetchAvailablePlugins" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaFetchAvailablePlugins_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// A synchronous resource action. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaFetchAvailablePluginsViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/fetchAvailablePlugins" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaFetchAvailablePlugins_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// A synchronous resource action. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaFetchAvailablePluginsViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/fetchAvailablePlugins" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaFetchAvailablePluginsWithResult_Call (request, eventListener,sender); + } + } + + /// A synchronous resource action. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaFetchAvailablePluginsWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/fetchAvailablePlugins" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaFetchAvailablePluginsWithResult_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.Dashboard.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 GrafanaFetchAvailablePluginsWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaAvailablePluginListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaFetchAvailablePlugins_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaAvailablePluginListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 GrafanaFetchAvailablePlugins_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// Get the properties of a specific workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaGet(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get the properties of a specific workspace for Grafana 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaGetViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get the properties of a specific workspace for Grafana resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get the properties of a specific workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaGetWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaGetWithResult_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.Dashboard.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 GrafanaGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaGet_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 GrafanaGet_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// List all resources of workspaces for Grafana under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaList(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List all resources of workspaces for Grafana under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListByResourceGroup(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List all resources of workspaces for Grafana under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListByResourceGroupViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana$", 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.Dashboard/grafana'"); + } + + // 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.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List all resources of workspaces for Grafana under the specified resource group. + /// + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListByResourceGroupViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana$", 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.Dashboard/grafana'"); + } + + // 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.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// + /// List all resources of workspaces for Grafana under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListByResourceGroupWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaListByResourceGroupWithResult_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.Dashboard.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 GrafanaListByResourceGroupWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaListByResourceGroup_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + } + } + + /// List all resources of workspaces for Grafana under the specified subscription. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Dashboard/grafana$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/grafana'"); + } + + // 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.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all resources of workspaces for Grafana under the specified subscription. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Dashboard/grafana$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/grafana'"); + } + + // 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.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaListWithResult_Call (request, eventListener,sender); + } + } + + /// List all resources of workspaces for Grafana under the specified 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaListWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Dashboard/grafana" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaListWithResult_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.Dashboard.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 GrafanaListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaList_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaList_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + } + } + + /// Update a workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The parameters for a PATCH request to a grafana 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.Dashboard.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 GrafanaUpdate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a workspace for Grafana resource. + /// + /// The parameters for a PATCH request to a grafana 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.Dashboard.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 GrafanaUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a workspace for Grafana resource. + /// + /// The parameters for a PATCH request to a grafana resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// Json string supplied to the GrafanaUpdate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaUpdateViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GrafanaUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// Json string supplied to the GrafanaUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GrafanaUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a workspace for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The parameters for a PATCH request to a grafana resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 GrafanaUpdateWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GrafanaUpdateWithResult_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.Dashboard.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 GrafanaUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 GrafanaUpdate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The parameters for a PATCH request to a grafana 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 GrafanaUpdate_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// create a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// The integration fabric resource type. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabricsCreate(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a IntegrationFabric + /// + /// The integration fabric resource type. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabricsCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a IntegrationFabric + /// + /// The integration fabric resource type. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabricsCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// Json string supplied to the IntegrationFabricsCreate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsCreateViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// Json string supplied to the IntegrationFabricsCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// The integration fabric resource type. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabricsCreateWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsCreateWithResult_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.Dashboard.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 IntegrationFabricsCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 IntegrationFabricsCreate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// The integration fabric resource type. + /// 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 IntegrationFabricsCreate_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(integrationFabricName),integrationFabricName); + await eventListener.AssertRegEx(nameof(integrationFabricName), integrationFabricName, @"^[a-zA-Z][a-z0-9A-Z-]{0,18}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsDelete(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a IntegrationFabric + /// + /// 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsDeleteViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsDelete_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.Dashboard.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 IntegrationFabricsDelete_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// 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 IntegrationFabricsDelete_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(integrationFabricName),integrationFabricName); + await eventListener.AssertRegEx(nameof(integrationFabricName), integrationFabricName, @"^[a-zA-Z][a-z0-9A-Z-]{0,18}[a-z0-9A-Z]$"); + } + } + + /// Get a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsGet(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a IntegrationFabric + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsGetViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a IntegrationFabric + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsGetWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsGetWithResult_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.Dashboard.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 IntegrationFabricsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 IntegrationFabricsGet_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// 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 IntegrationFabricsGet_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(integrationFabricName),integrationFabricName); + await eventListener.AssertRegEx(nameof(integrationFabricName), integrationFabricName, @"^[a-zA-Z][a-z0-9A-Z-]{0,18}[a-z0-9A-Z]$"); + } + } + + /// List IntegrationFabric resources by ManagedGrafana + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsList(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List IntegrationFabric resources by ManagedGrafana + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsListViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List IntegrationFabric resources by ManagedGrafana + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsListWithResult_Call (request, eventListener,sender); + } + } + + /// List IntegrationFabric resources by ManagedGrafana + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsListWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsListWithResult_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.Dashboard.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 IntegrationFabricsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 IntegrationFabricsList_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 IntegrationFabricsList_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// update a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// The parameters for a PATCH request to a Integration Fabric 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.Dashboard.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 IntegrationFabricsUpdate(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a IntegrationFabric + /// + /// The parameters for a PATCH request to a Integration Fabric 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.Dashboard.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 IntegrationFabricsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a IntegrationFabric + /// + /// The parameters for a PATCH request to a Integration Fabric resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabricsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/integrationFabrics/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var integrationFabricName = _match.Groups["integrationFabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/integrationFabrics/" + + integrationFabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// Json string supplied to the IntegrationFabricsUpdate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IntegrationFabricsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// Json string supplied to the IntegrationFabricsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IntegrationFabricsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a IntegrationFabric + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// The parameters for a PATCH request to a Integration Fabric resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabricsUpdateWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/integrationFabrics/" + + global::System.Uri.EscapeDataString(integrationFabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IntegrationFabricsUpdateWithResult_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.Dashboard.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 IntegrationFabricsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 IntegrationFabricsUpdate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The integration fabric name of Azure Managed Grafana. + /// The parameters for a PATCH request to a Integration Fabric 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 IntegrationFabricsUpdate_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string integrationFabricName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(integrationFabricName),integrationFabricName); + await eventListener.AssertRegEx(nameof(integrationFabricName), integrationFabricName, @"^[a-zA-Z][a-z0-9A-Z-]{0,18}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// The managed dashboard resource type. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsCreate(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// + /// The managed dashboard resource type. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// + /// The managed dashboard resource type. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedDashboardsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// Json string supplied to the ManagedDashboardsCreate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedDashboardsCreateViaJsonString(string subscriptionId, string resourceGroupName, string dashboardName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// Json string supplied to the ManagedDashboardsCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedDashboardsCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string dashboardName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedDashboardsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// The managed dashboard resource type. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsCreateWithResult(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedDashboardsCreateWithResult_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.Dashboard.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 ManagedDashboardsCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 ManagedDashboardsCreate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The name of the Azure Managed Dashboard. + /// The managed dashboard resource type. + /// 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 ManagedDashboardsCreate_Validate(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(dashboardName),dashboardName); + await eventListener.AssertRegEx(nameof(dashboardName), dashboardName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a dashboard for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedDashboardsDelete(string subscriptionId, string resourceGroupName, string dashboardName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a dashboard for Grafana resource. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedDashboardsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The name of the Azure Managed Dashboard. + /// 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 ManagedDashboardsDelete_Validate(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(dashboardName),dashboardName); + await eventListener.AssertRegEx(nameof(dashboardName), dashboardName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// update a dashboard for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// The parameters for a PATCH request to a managed dashboard 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.Dashboard.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 ManagedDashboardsUpdate(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a dashboard for Grafana resource. + /// + /// The parameters for a PATCH request to a managed dashboard 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.Dashboard.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 ManagedDashboardsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a dashboard for Grafana resource. + /// + /// The parameters for a PATCH request to a managed dashboard resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/dashboards/(?[^/]+)$", 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.Dashboard/dashboards/{dashboardName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var dashboardName = _match.Groups["dashboardName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/dashboards/" + + dashboardName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedDashboardsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a dashboard for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// Json string supplied to the ManagedDashboardsUpdate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedDashboardsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string dashboardName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedDashboardsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a dashboard for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// Json string supplied to the ManagedDashboardsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedDashboardsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string dashboardName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedDashboardsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a dashboard for Grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure Managed Dashboard. + /// The parameters for a PATCH request to a managed dashboard resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboardsUpdateWithResult(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/dashboards/" + + global::System.Uri.EscapeDataString(dashboardName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedDashboardsUpdateWithResult_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.Dashboard.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 ManagedDashboardsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 ManagedDashboardsUpdate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The name of the Azure Managed Dashboard. + /// The parameters for a PATCH request to a managed dashboard 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 ManagedDashboardsUpdate_Validate(string subscriptionId, string resourceGroupName, string dashboardName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(dashboardName),dashboardName); + await eventListener.AssertRegEx(nameof(dashboardName), dashboardName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// create a managed private endpoint for a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// The managed private endpoint to be created or 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.Dashboard.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 ManagedPrivateEndpointsCreate(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a managed private endpoint for a grafana resource. + /// + /// The managed private endpoint to be created or 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.Dashboard.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 ManagedPrivateEndpointsCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a managed private endpoint for a grafana resource. + /// + /// The managed private endpoint to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a managed private endpoint for a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Json string supplied to the ManagedPrivateEndpointsCreate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsCreateViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a managed private endpoint for a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Json string supplied to the ManagedPrivateEndpointsCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a managed private endpoint for a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// The managed private endpoint to be created or updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsCreateWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsCreateWithResult_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.Dashboard.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 ManagedPrivateEndpointsCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // declared final-state-via: original-uri + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 ManagedPrivateEndpointsCreate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: original-uri + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// The managed private endpoint to be created or 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 ManagedPrivateEndpointsCreate_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(managedPrivateEndpointName),managedPrivateEndpointName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a managed private endpoint for a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsDelete(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a managed private endpoint for a grafana resource. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// 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 ManagedPrivateEndpointsDelete_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(managedPrivateEndpointName),managedPrivateEndpointName); + } + } + + /// Get a specific managed private endpoint of a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsGet(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a specific managed private endpoint of a grafana 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsGetViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a specific managed private endpoint of a grafana resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a specific managed private endpoint of a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsGetWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsGetWithResult_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.Dashboard.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 ManagedPrivateEndpointsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 ManagedPrivateEndpointsGet_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// 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 ManagedPrivateEndpointsGet_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(managedPrivateEndpointName),managedPrivateEndpointName); + } + } + + /// List all managed private endpoints of a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsList(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all managed private endpoints of a grafana 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsListViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all managed private endpoints of a grafana resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsListWithResult_Call (request, eventListener,sender); + } + } + + /// List all managed private endpoints of a grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsListWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsListWithResult_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.Dashboard.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 ManagedPrivateEndpointsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 ManagedPrivateEndpointsList_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelListResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 ManagedPrivateEndpointsList_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// + /// Refresh and sync managed private endpoints of a grafana resource to latest state. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsRefresh(string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/refreshManagedPrivateEndpoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsRefresh_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Refresh and sync managed private endpoints of a grafana resource to latest state. + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsRefreshViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/refreshManagedPrivateEndpoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsRefresh_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsRefresh_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 ManagedPrivateEndpointsRefresh_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// update a managed private endpoint for an existing grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Properties that can be updated to an existing managed private endpoint. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsUpdate(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a managed private endpoint for an existing grafana resource. + /// + /// Properties that can be updated to an existing managed private endpoint. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a managed private endpoint for an existing grafana resource. + /// + /// Properties that can be updated to an existing managed private endpoint. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/managedPrivateEndpoints/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var managedPrivateEndpointName = _match.Groups["managedPrivateEndpointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/managedPrivateEndpoints/" + + managedPrivateEndpointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a managed private endpoint for an existing grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Json string supplied to the ManagedPrivateEndpointsUpdate 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagedPrivateEndpointsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a managed private endpoint for an existing grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Json string supplied to the ManagedPrivateEndpointsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ManagedPrivateEndpointsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a managed private endpoint for an existing grafana resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Properties that can be updated to an existing managed private endpoint. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointsUpdateWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/managedPrivateEndpoints/" + + global::System.Uri.EscapeDataString(managedPrivateEndpointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ManagedPrivateEndpointsUpdateWithResult_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.Dashboard.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 ManagedPrivateEndpointsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 ManagedPrivateEndpointsUpdate_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The managed private endpoint name of Azure Managed Grafana. + /// Properties that can be updated to an existing managed private endpoint. + /// 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 ManagedPrivateEndpointsUpdate_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string managedPrivateEndpointName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(managedPrivateEndpointName),managedPrivateEndpointName); + 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.Dashboard.Runtime.ISendAsync pipeline to 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Dashboard/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.ISendAsync pipeline to 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Dashboard/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Dashboard/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Dashboard/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.ISendAsync pipeline to 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Dashboard/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Dashboard/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Dashboard/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.ISendAsync pipeline to 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Dashboard/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// Manual approve private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// The Private Endpoint Connection 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.Dashboard.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 PrivateEndpointConnectionsApprove(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsApprove_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Manual approve private endpoint connection + /// + /// The Private Endpoint Connection 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.Dashboard.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 PrivateEndpointConnectionsApproveViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsApprove_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Manual approve private endpoint connection + /// + /// The Private Endpoint Connection resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 PrivateEndpointConnectionsApproveViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsApproveWithResult_Call (request, eventListener,sender); + } + } + + /// Manual approve private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// Json string supplied to the PrivateEndpointConnectionsApprove 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsApproveViaJsonString(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, 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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsApprove_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Manual approve private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// Json string supplied to the PrivateEndpointConnectionsApprove operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsApproveViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsApproveWithResult_Call (request, eventListener,sender); + } + } + + /// Manual approve private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// The Private Endpoint Connection resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 PrivateEndpointConnectionsApproveWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsApproveWithResult_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.Dashboard.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 PrivateEndpointConnectionsApproveWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 PrivateEndpointConnectionsApprove_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// The Private Endpoint Connection 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 PrivateEndpointConnectionsApprove_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection body, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionName),privateEndpointConnectionName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsDelete(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete private endpoint connection + /// + /// 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsDeleteViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsDelete_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.Dashboard.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 PrivateEndpointConnectionsDelete_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// 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 PrivateEndpointConnectionsDelete_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionName),privateEndpointConnectionName); + } + } + + /// Get private endpoint connections. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGet(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get private endpoint connections. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGetViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get private endpoint connections. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get private endpoint connections. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGetWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsGetWithResult_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.Dashboard.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 PrivateEndpointConnectionsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 PrivateEndpointConnectionsGet_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// The private endpoint connection name of Azure Managed Grafana. + /// 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 PrivateEndpointConnectionsGet_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionName),privateEndpointConnectionName); + } + } + + /// Get private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsList(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get private endpoint connection + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsListViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get private endpoint connection + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateEndpointConnections$", 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.Dashboard/grafana/{workspaceName}/privateEndpointConnections'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsListWithResult_Call (request, eventListener,sender); + } + } + + /// Get private endpoint connection + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsListWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsListWithResult_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.Dashboard.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 PrivateEndpointConnectionsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 PrivateEndpointConnectionsList_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 PrivateEndpointConnectionsList_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + + /// Get specific private link resource information for this grafana resource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// A sequence of textual characters. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGet(string subscriptionId, string resourceGroupName, string workspaceName, string privateLinkResourceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateLinkResources/" + + global::System.Uri.EscapeDataString(privateLinkResourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get specific private link resource information for this grafana 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGetViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateLinkResources/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateLinkResources/{privateLinkResourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateLinkResourceName = _match.Groups["privateLinkResourceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateLinkResources/" + + privateLinkResourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get specific private link resource information for this grafana resource + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateLinkResources/(?[^/]+)$", 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.Dashboard/grafana/{workspaceName}/privateLinkResources/{privateLinkResourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + var privateLinkResourceName = _match.Groups["privateLinkResourceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateLinkResources/" + + privateLinkResourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get specific private link resource information for this grafana resource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// A sequence of textual characters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGetWithResult(string subscriptionId, string resourceGroupName, string workspaceName, string privateLinkResourceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateLinkResources/" + + global::System.Uri.EscapeDataString(privateLinkResourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesGetWithResult_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.Dashboard.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 PrivateLinkResourcesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 PrivateLinkResourcesGet_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// A sequence of textual characters. + /// 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 PrivateLinkResourcesGet_Validate(string subscriptionId, string resourceGroupName, string workspaceName, string privateLinkResourceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + await eventListener.AssertNotNull(nameof(privateLinkResourceName),privateLinkResourceName); + } + } + + /// List all private link resources information for this grafana resource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesList(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all private link resources information for this grafana 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.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesListViaIdentity(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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateLinkResources$", 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.Dashboard/grafana/{workspaceName}/privateLinkResources'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List all private link resources information for this grafana resource + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.Dashboard/grafana/(?[^/]+)/privateLinkResources$", 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.Dashboard/grafana/{workspaceName}/privateLinkResources'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var workspaceName = _match.Groups["workspaceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.Dashboard/grafana/" + + workspaceName + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesListWithResult_Call (request, eventListener,sender); + } + } + + /// List all private link resources information for this grafana resource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The workspace name of Azure Managed Grafana. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesListWithResult(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-11-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/Microsoft.Dashboard/grafana/" + + global::System.Uri.EscapeDataString(workspaceName) + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesListWithResult_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.Dashboard.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 PrivateLinkResourcesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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 PrivateLinkResourcesList_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.Dashboard.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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. + /// The workspace name of Azure Managed Grafana. + /// 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 PrivateLinkResourcesList_Validate(string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertRegEx(nameof(workspaceName), workspaceName, @"^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$"); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..61d53254604 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..478d80dba67 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..403820f5977 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..a236d4724db --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.PowerShell.cs new file mode 100644 index 00000000000..defc6ce7e99 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Integrations for Azure Monitor Workspace. + [System.ComponentModel.TypeConverter(typeof(AzureMonitorWorkspaceIntegrationTypeConverter))] + public partial class AzureMonitorWorkspaceIntegration + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AzureMonitorWorkspaceIntegration(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AzureMonitorWorkspaceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegrationInternal)this).AzureMonitorWorkspaceResourceId = (string) content.GetValueForProperty("AzureMonitorWorkspaceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegrationInternal)this).AzureMonitorWorkspaceResourceId, 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 AzureMonitorWorkspaceIntegration(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AzureMonitorWorkspaceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegrationInternal)this).AzureMonitorWorkspaceResourceId = (string) content.GetValueForProperty("AzureMonitorWorkspaceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegrationInternal)this).AzureMonitorWorkspaceResourceId, 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.Dashboard.Models.IAzureMonitorWorkspaceIntegration DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AzureMonitorWorkspaceIntegration(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AzureMonitorWorkspaceIntegration(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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(); + } + } + /// Integrations for Azure Monitor Workspace. + [System.ComponentModel.TypeConverter(typeof(AzureMonitorWorkspaceIntegrationTypeConverter))] + public partial interface IAzureMonitorWorkspaceIntegration + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.TypeConverter.cs new file mode 100644 index 00000000000..f97c45e3848 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AzureMonitorWorkspaceIntegrationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IAzureMonitorWorkspaceIntegration ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AzureMonitorWorkspaceIntegration.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AzureMonitorWorkspaceIntegration.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AzureMonitorWorkspaceIntegration.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.cs new file mode 100644 index 00000000000..f2367f7576d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Integrations for Azure Monitor Workspace. + public partial class AzureMonitorWorkspaceIntegration : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegrationInternal + { + + /// Backing field for property. + private string _azureMonitorWorkspaceResourceId; + + /// The resource Id of the connected Azure Monitor Workspace. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string AzureMonitorWorkspaceResourceId { get => this._azureMonitorWorkspaceResourceId; set => this._azureMonitorWorkspaceResourceId = value; } + + /// Creates an new instance. + public AzureMonitorWorkspaceIntegration() + { + + } + } + /// Integrations for Azure Monitor Workspace. + public partial interface IAzureMonitorWorkspaceIntegration : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The resource Id of the connected Azure Monitor Workspace. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource Id of the connected Azure Monitor Workspace.", + SerializedName = @"azureMonitorWorkspaceResourceId", + PossibleTypes = new [] { typeof(string) })] + string AzureMonitorWorkspaceResourceId { get; set; } + + } + /// Integrations for Azure Monitor Workspace. + internal partial interface IAzureMonitorWorkspaceIntegrationInternal + + { + /// The resource Id of the connected Azure Monitor Workspace. + string AzureMonitorWorkspaceResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.json.cs new file mode 100644 index 00000000000..be560522280 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/AzureMonitorWorkspaceIntegration.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Integrations for Azure Monitor Workspace. + public partial class AzureMonitorWorkspaceIntegration + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal AzureMonitorWorkspaceIntegration(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_azureMonitorWorkspaceResourceId = If( json?.PropertyT("azureMonitorWorkspaceResourceId"), out var __jsonAzureMonitorWorkspaceResourceId) ? (string)__jsonAzureMonitorWorkspaceResourceId : (string)_azureMonitorWorkspaceResourceId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new AzureMonitorWorkspaceIntegration(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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._azureMonitorWorkspaceResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._azureMonitorWorkspaceResourceId.ToString()) : null, "azureMonitorWorkspaceResourceId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.PowerShell.cs new file mode 100644 index 00000000000..2c7d8d17725 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.PowerShell.cs @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(DashboardIdentityTypeConverter))] + public partial class DashboardIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 DashboardIdentity(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.Dashboard.Models.IDashboardIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("WorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).WorkspaceName = (string) content.GetValueForProperty("WorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).WorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("ManagedPrivateEndpointName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ManagedPrivateEndpointName = (string) content.GetValueForProperty("ManagedPrivateEndpointName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ManagedPrivateEndpointName, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointConnectionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateEndpointConnectionName = (string) content.GetValueForProperty("PrivateEndpointConnectionName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateEndpointConnectionName, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateLinkResourceName = (string) content.GetValueForProperty("PrivateLinkResourceName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateLinkResourceName, global::System.Convert.ToString); + } + if (content.Contains("IntegrationFabricName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).IntegrationFabricName = (string) content.GetValueForProperty("IntegrationFabricName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).IntegrationFabricName, global::System.Convert.ToString); + } + if (content.Contains("DashboardName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).DashboardName = (string) content.GetValueForProperty("DashboardName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).DashboardName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)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 DashboardIdentity(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.Dashboard.Models.IDashboardIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("WorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).WorkspaceName = (string) content.GetValueForProperty("WorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).WorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("ManagedPrivateEndpointName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ManagedPrivateEndpointName = (string) content.GetValueForProperty("ManagedPrivateEndpointName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).ManagedPrivateEndpointName, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointConnectionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateEndpointConnectionName = (string) content.GetValueForProperty("PrivateEndpointConnectionName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateEndpointConnectionName, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateLinkResourceName = (string) content.GetValueForProperty("PrivateLinkResourceName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).PrivateLinkResourceName, global::System.Convert.ToString); + } + if (content.Contains("IntegrationFabricName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).IntegrationFabricName = (string) content.GetValueForProperty("IntegrationFabricName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).IntegrationFabricName, global::System.Convert.ToString); + } + if (content.Contains("DashboardName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).DashboardName = (string) content.GetValueForProperty("DashboardName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).DashboardName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal)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.Dashboard.Models.IDashboardIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DashboardIdentity(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DashboardIdentity(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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(DashboardIdentityTypeConverter))] + public partial interface IDashboardIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.TypeConverter.cs new file mode 100644 index 00000000000..d77163960f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DashboardIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IDashboardIdentity 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 DashboardIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DashboardIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DashboardIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DashboardIdentity.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.cs new file mode 100644 index 00000000000..2a17eff5443 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.cs @@ -0,0 +1,209 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class DashboardIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentityInternal + { + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _integrationFabricName; + + /// The integration fabric name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string IntegrationFabricName { get => this._integrationFabricName; set => this._integrationFabricName = value; } + + /// Backing field for property. + private string _managedPrivateEndpointName; + + /// The managed private endpoint name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ManagedPrivateEndpointName { get => this._managedPrivateEndpointName; set => this._managedPrivateEndpointName = value; } + + /// Backing field for property. + private string _privateEndpointConnectionName; + + /// The private endpoint connection name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PrivateEndpointConnectionName { get => this._privateEndpointConnectionName; set => this._privateEndpointConnectionName = value; } + + /// Backing field for property. + private string _privateLinkResourceName; + + /// A sequence of textual characters. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PrivateLinkResourceName { get => this._privateLinkResourceName; set => this._privateLinkResourceName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// Creates an new instance. + public DashboardIdentity() + { + + } + } + public partial interface IDashboardIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The name of the Azure Managed Dashboard. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + string DashboardName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 integration fabric name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + string IntegrationFabricName { get; set; } + /// The managed private endpoint name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + string ManagedPrivateEndpointName { get; set; } + /// The private endpoint connection name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private endpoint connection name of Azure Managed Grafana.", + SerializedName = @"privateEndpointConnectionName", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointConnectionName { get; set; } + /// A sequence of textual characters. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A sequence of textual characters.", + SerializedName = @"privateLinkResourceName", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkResourceName { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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; } + /// The workspace name of Azure Managed Grafana. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + string WorkspaceName { get; set; } + + } + internal partial interface IDashboardIdentityInternal + + { + /// The name of the Azure Managed Dashboard. + string DashboardName { get; set; } + /// Resource identity path + string Id { get; set; } + /// The integration fabric name of Azure Managed Grafana. + string IntegrationFabricName { get; set; } + /// The managed private endpoint name of Azure Managed Grafana. + string ManagedPrivateEndpointName { get; set; } + /// The private endpoint connection name of Azure Managed Grafana. + string PrivateEndpointConnectionName { get; set; } + /// A sequence of textual characters. + string PrivateLinkResourceName { 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; } + /// The workspace name of Azure Managed Grafana. + string WorkspaceName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.json.cs new file mode 100644 index 00000000000..8dc9ebf0d2e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/DashboardIdentity.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class DashboardIdentity + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal DashboardIdentity(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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;} + {_workspaceName = If( json?.PropertyT("workspaceName"), out var __jsonWorkspaceName) ? (string)__jsonWorkspaceName : (string)_workspaceName;} + {_managedPrivateEndpointName = If( json?.PropertyT("managedPrivateEndpointName"), out var __jsonManagedPrivateEndpointName) ? (string)__jsonManagedPrivateEndpointName : (string)_managedPrivateEndpointName;} + {_privateEndpointConnectionName = If( json?.PropertyT("privateEndpointConnectionName"), out var __jsonPrivateEndpointConnectionName) ? (string)__jsonPrivateEndpointConnectionName : (string)_privateEndpointConnectionName;} + {_privateLinkResourceName = If( json?.PropertyT("privateLinkResourceName"), out var __jsonPrivateLinkResourceName) ? (string)__jsonPrivateLinkResourceName : (string)_privateLinkResourceName;} + {_integrationFabricName = If( json?.PropertyT("integrationFabricName"), out var __jsonIntegrationFabricName) ? (string)__jsonIntegrationFabricName : (string)_integrationFabricName;} + {_dashboardName = If( json?.PropertyT("dashboardName"), out var __jsonDashboardName) ? (string)__jsonDashboardName : (string)_dashboardName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new DashboardIdentity(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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._workspaceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._workspaceName.ToString()) : null, "workspaceName" ,container.Add ); + AddIf( null != (((object)this._managedPrivateEndpointName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._managedPrivateEndpointName.ToString()) : null, "managedPrivateEndpointName" ,container.Add ); + AddIf( null != (((object)this._privateEndpointConnectionName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._privateEndpointConnectionName.ToString()) : null, "privateEndpointConnectionName" ,container.Add ); + AddIf( null != (((object)this._privateLinkResourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._privateLinkResourceName.ToString()) : null, "privateLinkResourceName" ,container.Add ); + AddIf( null != (((object)this._integrationFabricName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._integrationFabricName.ToString()) : null, "integrationFabricName" ,container.Add ); + AddIf( null != (((object)this._dashboardName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._dashboardName.ToString()) : null, "dashboardName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.PowerShell.cs new file mode 100644 index 00000000000..afb141674ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Enterprise settings of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(EnterpriseConfigurationsTypeConverter))] + public partial class EnterpriseConfigurations + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IEnterpriseConfigurations DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EnterpriseConfigurations(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EnterpriseConfigurations(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EnterpriseConfigurations(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplacePlanId = (string) content.GetValueForProperty("MarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplaceAutoRenew = (string) content.GetValueForProperty("MarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplaceAutoRenew, 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 EnterpriseConfigurations(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplacePlanId = (string) content.GetValueForProperty("MarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplaceAutoRenew = (string) content.GetValueForProperty("MarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)this).MarketplaceAutoRenew, 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.Dashboard.Models.IEnterpriseConfigurations FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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(); + } + } + /// Enterprise settings of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(EnterpriseConfigurationsTypeConverter))] + public partial interface IEnterpriseConfigurations + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.TypeConverter.cs new file mode 100644 index 00000000000..b1feefbd75c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EnterpriseConfigurationsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IEnterpriseConfigurations ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EnterpriseConfigurations.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EnterpriseConfigurations.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EnterpriseConfigurations.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.cs new file mode 100644 index 00000000000..853afd0047a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Enterprise settings of a Grafana instance + public partial class EnterpriseConfigurations : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal + { + + /// Backing field for property. + private string _marketplaceAutoRenew; + + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string MarketplaceAutoRenew { get => this._marketplaceAutoRenew; set => this._marketplaceAutoRenew = value; } + + /// Backing field for property. + private string _marketplacePlanId; + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string MarketplacePlanId { get => this._marketplacePlanId; set => this._marketplacePlanId = value; } + + /// Creates an new instance. + public EnterpriseConfigurations() + { + + } + } + /// Enterprise settings of a Grafana instance + public partial interface IEnterpriseConfigurations : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string MarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + string MarketplacePlanId { get; set; } + + } + /// Enterprise settings of a Grafana instance + internal partial interface IEnterpriseConfigurationsInternal + + { + /// The AutoRenew setting of the Enterprise subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string MarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + string MarketplacePlanId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.json.cs new file mode 100644 index 00000000000..7ec45fc76c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseConfigurations.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Enterprise settings of a Grafana instance + public partial class EnterpriseConfigurations + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal EnterpriseConfigurations(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplacePlanId = If( json?.PropertyT("marketplacePlanId"), out var __jsonMarketplacePlanId) ? (string)__jsonMarketplacePlanId : (string)_marketplacePlanId;} + {_marketplaceAutoRenew = If( json?.PropertyT("marketplaceAutoRenew"), out var __jsonMarketplaceAutoRenew) ? (string)__jsonMarketplaceAutoRenew : (string)_marketplaceAutoRenew;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new EnterpriseConfigurations(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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._marketplacePlanId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._marketplacePlanId.ToString()) : null, "marketplacePlanId" ,container.Add ); + AddIf( null != (((object)this._marketplaceAutoRenew)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._marketplaceAutoRenew.ToString()) : null, "marketplaceAutoRenew" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.PowerShell.cs new file mode 100644 index 00000000000..7a5cdd5a8ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Enterprise details of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(EnterpriseDetailsTypeConverter))] + public partial class EnterpriseDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IEnterpriseDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EnterpriseDetails(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EnterpriseDetails(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EnterpriseDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SaasSubscriptionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaasSubscriptionDetail = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails) content.GetValueForProperty("SaasSubscriptionDetail",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaasSubscriptionDetail, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SaasSubscriptionDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceTrialQuota")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuota = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota) content.GetValueForProperty("MarketplaceTrialQuota",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuota, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.MarketplaceTrialQuotaTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceTrialQuotaAvailablePromotion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaAvailablePromotion = (string) content.GetValueForProperty("MarketplaceTrialQuotaAvailablePromotion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaAvailablePromotion, global::System.Convert.ToString); + } + if (content.Contains("SaaSubscriptionDetailTerm")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailTerm = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm) content.GetValueForProperty("SaaSubscriptionDetailTerm",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailTerm, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTermTypeConverter.ConvertFrom); + } + if (content.Contains("SaaSubscriptionDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPlanId = (string) content.GetValueForProperty("SaaSubscriptionDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("SaaSubscriptionDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailOfferId = (string) content.GetValueForProperty("SaaSubscriptionDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("SaaSubscriptionDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPublisherId = (string) content.GetValueForProperty("SaaSubscriptionDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceTrialQuotaGrafanaResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaGrafanaResourceId = (string) content.GetValueForProperty("MarketplaceTrialQuotaGrafanaResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaGrafanaResourceId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceTrialQuotaTrialStartAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialStartAt = (global::System.DateTime?) content.GetValueForProperty("MarketplaceTrialQuotaTrialStartAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialStartAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("MarketplaceTrialQuotaTrialEndAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialEndAt = (global::System.DateTime?) content.GetValueForProperty("MarketplaceTrialQuotaTrialEndAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialEndAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermStartDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermStartDate = (global::System.DateTime?) content.GetValueForProperty("TermStartDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermStartDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TermEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermEndDate = (global::System.DateTime?) content.GetValueForProperty("TermEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermEndDate, (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 EnterpriseDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SaasSubscriptionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaasSubscriptionDetail = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails) content.GetValueForProperty("SaasSubscriptionDetail",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaasSubscriptionDetail, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SaasSubscriptionDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceTrialQuota")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuota = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota) content.GetValueForProperty("MarketplaceTrialQuota",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuota, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.MarketplaceTrialQuotaTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceTrialQuotaAvailablePromotion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaAvailablePromotion = (string) content.GetValueForProperty("MarketplaceTrialQuotaAvailablePromotion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaAvailablePromotion, global::System.Convert.ToString); + } + if (content.Contains("SaaSubscriptionDetailTerm")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailTerm = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm) content.GetValueForProperty("SaaSubscriptionDetailTerm",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailTerm, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTermTypeConverter.ConvertFrom); + } + if (content.Contains("SaaSubscriptionDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPlanId = (string) content.GetValueForProperty("SaaSubscriptionDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("SaaSubscriptionDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailOfferId = (string) content.GetValueForProperty("SaaSubscriptionDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("SaaSubscriptionDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPublisherId = (string) content.GetValueForProperty("SaaSubscriptionDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).SaaSubscriptionDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceTrialQuotaGrafanaResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaGrafanaResourceId = (string) content.GetValueForProperty("MarketplaceTrialQuotaGrafanaResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaGrafanaResourceId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceTrialQuotaTrialStartAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialStartAt = (global::System.DateTime?) content.GetValueForProperty("MarketplaceTrialQuotaTrialStartAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialStartAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("MarketplaceTrialQuotaTrialEndAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialEndAt = (global::System.DateTime?) content.GetValueForProperty("MarketplaceTrialQuotaTrialEndAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).MarketplaceTrialQuotaTrialEndAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermStartDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermStartDate = (global::System.DateTime?) content.GetValueForProperty("TermStartDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermStartDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TermEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermEndDate = (global::System.DateTime?) content.GetValueForProperty("TermEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal)this).TermEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + 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.Dashboard.Models.IEnterpriseDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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(); + } + } + /// Enterprise details of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(EnterpriseDetailsTypeConverter))] + public partial interface IEnterpriseDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.TypeConverter.cs new file mode 100644 index 00000000000..cc342fedfcd --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EnterpriseDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IEnterpriseDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EnterpriseDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EnterpriseDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EnterpriseDetails.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.cs new file mode 100644 index 00000000000..f500fd6b0e1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Enterprise details of a Grafana instance + public partial class EnterpriseDetails : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota _marketplaceTrialQuota; + + /// + /// The allocation details of the per subscription free trial slot of the subscription. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota MarketplaceTrialQuota { get => (this._marketplaceTrialQuota = this._marketplaceTrialQuota ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.MarketplaceTrialQuota()); set => this._marketplaceTrialQuota = value; } + + /// Available enterprise promotion for the subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string MarketplaceTrialQuotaAvailablePromotion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).AvailablePromotion; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).AvailablePromotion = value ?? null; } + + /// Resource Id of the Grafana resource which is doing the trial. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string MarketplaceTrialQuotaGrafanaResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).GrafanaResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).GrafanaResourceId = value ?? null; } + + /// The date and time in UTC of when the trial ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? MarketplaceTrialQuotaTrialEndAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).TrialEndAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).TrialEndAt = value ?? default(global::System.DateTime); } + + /// The date and time in UTC of when the trial starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? MarketplaceTrialQuotaTrialStartAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).TrialStartAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)MarketplaceTrialQuota).TrialStartAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for MarketplaceTrialQuota + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal.MarketplaceTrialQuota { get => (this._marketplaceTrialQuota = this._marketplaceTrialQuota ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.MarketplaceTrialQuota()); set { {_marketplaceTrialQuota = value;} } } + + /// Internal Acessors for SaaSubscriptionDetailTerm + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal.SaaSubscriptionDetailTerm { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).Term; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).Term = value ?? null /* model class */; } + + /// Internal Acessors for SaasSubscriptionDetail + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetailsInternal.SaasSubscriptionDetail { get => (this._saasSubscriptionDetail = this._saasSubscriptionDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SaasSubscriptionDetails()); set { {_saasSubscriptionDetail = value;} } } + + /// The offer Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SaaSubscriptionDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).OfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).OfferId = value ?? null; } + + /// The plan Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SaaSubscriptionDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).PlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).PlanId = value ?? null; } + + /// The publisher Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SaaSubscriptionDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).PublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).PublisherId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails _saasSubscriptionDetail; + + /// SaaS subscription details of a Grafana instance + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails SaasSubscriptionDetail { get => (this._saasSubscriptionDetail = this._saasSubscriptionDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SaasSubscriptionDetails()); set => this._saasSubscriptionDetail = value; } + + /// The date and time in UTC of when the billing term ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? TermEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).TermEndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).TermEndDate = value ?? default(global::System.DateTime); } + + /// The date and time in UTC of when the billing term starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? TermStartDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).TermStartDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).TermStartDate = value ?? default(global::System.DateTime); } + + /// The unit of the billing term. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string TermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).TermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)SaasSubscriptionDetail).TermUnit = value ?? null; } + + /// Creates an new instance. + public EnterpriseDetails() + { + + } + } + /// Enterprise details of a Grafana instance + public partial interface IEnterpriseDetails : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Available enterprise promotion for the subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Available enterprise promotion for the subscription", + SerializedName = @"availablePromotion", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("None", "FreeTrial")] + string MarketplaceTrialQuotaAvailablePromotion { get; set; } + /// Resource Id of the Grafana resource which is doing the trial. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource Id of the Grafana resource which is doing the trial.", + SerializedName = @"grafanaResourceId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceTrialQuotaGrafanaResourceId { get; set; } + /// The date and time in UTC of when the trial ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the trial ends.", + SerializedName = @"trialEndAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? MarketplaceTrialQuotaTrialEndAt { get; set; } + /// The date and time in UTC of when the trial starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the trial starts.", + SerializedName = @"trialStartAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? MarketplaceTrialQuotaTrialStartAt { get; set; } + /// The offer Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The offer Id of the SaaS subscription.", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string SaaSubscriptionDetailOfferId { get; set; } + /// The plan Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The plan Id of the SaaS subscription.", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string SaaSubscriptionDetailPlanId { get; set; } + /// The publisher Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The publisher Id of the SaaS subscription.", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string SaaSubscriptionDetailPublisherId { get; set; } + /// The date and time in UTC of when the billing term ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the billing term ends.", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TermEndDate { get; set; } + /// The date and time in UTC of when the billing term starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the billing term starts.", + SerializedName = @"startDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TermStartDate { get; set; } + /// The unit of the billing term. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The unit of the billing term.", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string TermUnit { get; set; } + + } + /// Enterprise details of a Grafana instance + internal partial interface IEnterpriseDetailsInternal + + { + /// + /// The allocation details of the per subscription free trial slot of the subscription. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota MarketplaceTrialQuota { get; set; } + /// Available enterprise promotion for the subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("None", "FreeTrial")] + string MarketplaceTrialQuotaAvailablePromotion { get; set; } + /// Resource Id of the Grafana resource which is doing the trial. + string MarketplaceTrialQuotaGrafanaResourceId { get; set; } + /// The date and time in UTC of when the trial ends. + global::System.DateTime? MarketplaceTrialQuotaTrialEndAt { get; set; } + /// The date and time in UTC of when the trial starts. + global::System.DateTime? MarketplaceTrialQuotaTrialStartAt { get; set; } + /// The offer Id of the SaaS subscription. + string SaaSubscriptionDetailOfferId { get; set; } + /// The plan Id of the SaaS subscription. + string SaaSubscriptionDetailPlanId { get; set; } + /// The publisher Id of the SaaS subscription. + string SaaSubscriptionDetailPublisherId { get; set; } + /// The billing term of the SaaS Subscription. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm SaaSubscriptionDetailTerm { get; set; } + /// SaaS subscription details of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails SaasSubscriptionDetail { get; set; } + /// The date and time in UTC of when the billing term ends. + global::System.DateTime? TermEndDate { get; set; } + /// The date and time in UTC of when the billing term starts. + global::System.DateTime? TermStartDate { get; set; } + /// The unit of the billing term. + string TermUnit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.json.cs new file mode 100644 index 00000000000..fb14ff850f9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/EnterpriseDetails.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Enterprise details of a Grafana instance + public partial class EnterpriseDetails + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal EnterpriseDetails(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_saasSubscriptionDetail = If( json?.PropertyT("saasSubscriptionDetails"), out var __jsonSaasSubscriptionDetails) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SaasSubscriptionDetails.FromJson(__jsonSaasSubscriptionDetails) : _saasSubscriptionDetail;} + {_marketplaceTrialQuota = If( json?.PropertyT("marketplaceTrialQuota"), out var __jsonMarketplaceTrialQuota) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.MarketplaceTrialQuota.FromJson(__jsonMarketplaceTrialQuota) : _marketplaceTrialQuota;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new EnterpriseDetails(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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._saasSubscriptionDetail ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._saasSubscriptionDetail.ToJson(null,serializationMode) : null, "saasSubscriptionDetails" ,container.Add ); + AddIf( null != this._marketplaceTrialQuota ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._marketplaceTrialQuota.ToJson(null,serializationMode) : null, "marketplaceTrialQuota" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..e1709f812c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..92da669c6ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..bce51a00bfb --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..09dd67e2f10 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..49c5bb88db8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..5fd722eec4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..e61b3e06404 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..d30a2c5b58c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..5c58a682f16 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..a8d99677261 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..dc84e11f9c3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Message = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorDetailInternal)Error).Target = value ?? null; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..74f43017ea0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.PowerShell.cs new file mode 100644 index 00000000000..8760c816fe9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Available plugins of grafana + [System.ComponentModel.TypeConverter(typeof(GrafanaAvailablePluginTypeConverter))] + public partial class GrafanaAvailablePlugin + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IGrafanaAvailablePlugin DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GrafanaAvailablePlugin(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GrafanaAvailablePlugin(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GrafanaAvailablePlugin(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PluginId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).PluginId = (string) content.GetValueForProperty("PluginId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).PluginId, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)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 GrafanaAvailablePlugin(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PluginId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).PluginId = (string) content.GetValueForProperty("PluginId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).PluginId, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal)this).Name, 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.Dashboard.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(); + } + } + /// Available plugins of grafana + [System.ComponentModel.TypeConverter(typeof(GrafanaAvailablePluginTypeConverter))] + public partial interface IGrafanaAvailablePlugin + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.TypeConverter.cs new file mode 100644 index 00000000000..10cc39d1065 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GrafanaAvailablePluginTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IGrafanaAvailablePlugin ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GrafanaAvailablePlugin.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GrafanaAvailablePlugin.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GrafanaAvailablePlugin.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.cs new file mode 100644 index 00000000000..49aea82186f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Available plugins of grafana + public partial class GrafanaAvailablePlugin : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal + { + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for PluginId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginInternal.PluginId { get => this._pluginId; set { {_pluginId = value;} } } + + /// Backing field for property. + private string _name; + + /// Grafana plugin display name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _pluginId; + + /// Grafana plugin id + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PluginId { get => this._pluginId; } + + /// Creates an new instance. + public GrafanaAvailablePlugin() + { + + } + } + /// Available plugins of grafana + public partial interface IGrafanaAvailablePlugin : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Grafana plugin display name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Grafana plugin display name", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Grafana plugin id + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Grafana plugin id", + SerializedName = @"pluginId", + PossibleTypes = new [] { typeof(string) })] + string PluginId { get; } + + } + /// Available plugins of grafana + internal partial interface IGrafanaAvailablePluginInternal + + { + /// Grafana plugin display name + string Name { get; set; } + /// Grafana plugin id + string PluginId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.json.cs new file mode 100644 index 00000000000..6c49d046dba --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePlugin.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Available plugins of grafana + public partial class GrafanaAvailablePlugin + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new GrafanaAvailablePlugin(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal GrafanaAvailablePlugin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_pluginId = If( json?.PropertyT("pluginId"), out var __jsonPluginId) ? (string)__jsonPluginId : (string)_pluginId;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._pluginId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._pluginId.ToString()) : null, "pluginId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.PowerShell.cs new file mode 100644 index 00000000000..85a77a81f61 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(GrafanaAvailablePluginListResponseTypeConverter))] + public partial class GrafanaAvailablePluginListResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IGrafanaAvailablePluginListResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GrafanaAvailablePluginListResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GrafanaAvailablePluginListResponse(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GrafanaAvailablePluginListResponse(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.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaAvailablePluginTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)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 GrafanaAvailablePluginListResponse(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.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaAvailablePluginTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal)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.Dashboard.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(GrafanaAvailablePluginListResponseTypeConverter))] + public partial interface IGrafanaAvailablePluginListResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.TypeConverter.cs new file mode 100644 index 00000000000..8ac76757c0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GrafanaAvailablePluginListResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IGrafanaAvailablePluginListResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GrafanaAvailablePluginListResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GrafanaAvailablePluginListResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GrafanaAvailablePluginListResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.cs new file mode 100644 index 00000000000..8fa668fb66a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class GrafanaAvailablePluginListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponseInternal + { + + /// Backing field for property. + private string _nextLink; + + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// Array of GrafanaAvailablePlugin + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public GrafanaAvailablePluginListResponse() + { + + } + } + public partial interface IGrafanaAvailablePluginListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// Array of GrafanaAvailablePlugin + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Array of GrafanaAvailablePlugin", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePlugin) })] + System.Collections.Generic.List Value { get; set; } + + } + internal partial interface IGrafanaAvailablePluginListResponseInternal + + { + string NextLink { get; set; } + /// Array of GrafanaAvailablePlugin + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.json.cs new file mode 100644 index 00000000000..d573abaf834 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaAvailablePluginListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class GrafanaAvailablePluginListResponse + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new GrafanaAvailablePluginListResponse(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal GrafanaAvailablePluginListResponse(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IGrafanaAvailablePlugin) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaAvailablePlugin.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.PowerShell.cs new file mode 100644 index 00000000000..bcfb2846501 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.PowerShell.cs @@ -0,0 +1,298 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Server configurations of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(GrafanaConfigurationsTypeConverter))] + public partial class GrafanaConfigurations + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IGrafanaConfigurations DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GrafanaConfigurations(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GrafanaConfigurations(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GrafanaConfigurations(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Smtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Smtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("Smtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Smtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("Snapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Snapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("Snapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Snapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("Security")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Security = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("Security",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Security, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("UnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("UnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal GrafanaConfigurations(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Smtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Smtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("Smtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Smtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("Snapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Snapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("Snapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Snapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("Security")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Security = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("Security",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).Security, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("UnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("UnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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(); + } + } + /// Server configurations of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(GrafanaConfigurationsTypeConverter))] + public partial interface IGrafanaConfigurations + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.TypeConverter.cs new file mode 100644 index 00000000000..d510fe7ee5b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GrafanaConfigurationsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IGrafanaConfigurations ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GrafanaConfigurations.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GrafanaConfigurations.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GrafanaConfigurations.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.cs new file mode 100644 index 00000000000..02cc28f81ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Server configurations of a Grafana instance + public partial class GrafanaConfigurations : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal + { + + /// Internal Acessors for Security + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal.Security { get => (this._security = this._security ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Security()); set { {_security = value;} } } + + /// Internal Acessors for Smtp + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal.Smtp { get => (this._smtp = this._smtp ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Smtp()); set { {_smtp = value;} } } + + /// Internal Acessors for Snapshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal.Snapshot { get => (this._snapshot = this._snapshot ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Snapshots()); set { {_snapshot = value;} } } + + /// Internal Acessors for UnifiedAlertingScreenshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal.UnifiedAlertingScreenshot { get => (this._unifiedAlertingScreenshot = this._unifiedAlertingScreenshot ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshots()); set { {_unifiedAlertingScreenshot = value;} } } + + /// Internal Acessors for User + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal.User { get => (this._user = this._user ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Users()); set { {_user = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity _security; + + /// Grafana security settings + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Security { get => (this._security = this._security ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Security()); set => this._security = value; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SecurityCsrfAlwaysCheck { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal)Security).CsrfAlwaysCheck; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal)Security).CsrfAlwaysCheck = value ?? default(bool); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp _smtp; + + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Smtp { get => (this._smtp = this._smtp ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Smtp()); set => this._smtp = value; } + + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).Enabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).Enabled = value ?? default(bool); } + + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).FromAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).FromAddress = value ?? null; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).FromName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).FromName = value ?? null; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpHost { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).Host; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).Host = value ?? null; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Security.SecureString SmtpPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).Password; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).Password = value ?? null; } + + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpSkipVerify { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).SkipVerify; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).SkipVerify = value ?? default(bool); } + + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpStartTlsPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).StartTlsPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).StartTlsPolicy = value ?? null; } + + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).User; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)Smtp).User = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots _snapshot; + + /// Grafana Snapshots settings + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Snapshot { get => (this._snapshot = this._snapshot ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Snapshots()); set => this._snapshot = value; } + + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SnapshotExternalEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal)Snapshot).ExternalEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal)Snapshot).ExternalEnabled = value ?? default(bool); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots _unifiedAlertingScreenshot; + + /// Grafana Unified Alerting Screenshots settings + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots UnifiedAlertingScreenshot { get => (this._unifiedAlertingScreenshot = this._unifiedAlertingScreenshot ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshots()); set => this._unifiedAlertingScreenshot = value; } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UnifiedAlertingScreenshotCaptureEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal)UnifiedAlertingScreenshot).CaptureEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal)UnifiedAlertingScreenshot).CaptureEnabled = value ?? default(bool); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers _user; + + /// Grafana users settings + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers User { get => (this._user = this._user ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Users()); set => this._user = value; } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserEditorsCanAdmin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)User).EditorsCanAdmin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)User).EditorsCanAdmin = value ?? default(bool); } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserViewersCanEdit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)User).ViewersCanEdit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)User).ViewersCanEdit = value ?? default(bool); } + + /// Creates an new instance. + public GrafanaConfigurations() + { + + } + } + /// Server configurations of a Grafana instance + public partial interface IGrafanaConfigurations : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(bool) })] + bool? SecurityCsrfAlwaysCheck { get; set; } + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Address used when sending out emails + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification"" + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Verify SSL for SMTP server. Default is false + https://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The StartTLSPolicy setting of the SMTP configuration + https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SnapshotExternalEnabled { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(bool) })] + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(bool) })] + bool? UserViewersCanEdit { get; set; } + + } + /// Server configurations of a Grafana instance + internal partial interface IGrafanaConfigurationsInternal + + { + /// Grafana security settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Security { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + bool? SecurityCsrfAlwaysCheck { get; set; } + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Smtp { get; set; } + /// Enable this to allow Grafana to send email. Default is false + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + string SmtpUser { get; set; } + /// Grafana Snapshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Snapshot { get; set; } + /// Set to false to disable external snapshot publish endpoint + bool? SnapshotExternalEnabled { get; set; } + /// Grafana Unified Alerting Screenshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots UnifiedAlertingScreenshot { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// Grafana users settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers User { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + bool? UserViewersCanEdit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.json.cs new file mode 100644 index 00000000000..f4d7256dea1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaConfigurations.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Server configurations of a Grafana instance + public partial class GrafanaConfigurations + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new GrafanaConfigurations(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal GrafanaConfigurations(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_smtp = If( json?.PropertyT("smtp"), out var __jsonSmtp) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Smtp.FromJson(__jsonSmtp) : _smtp;} + {_snapshot = If( json?.PropertyT("snapshots"), out var __jsonSnapshots) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Snapshots.FromJson(__jsonSnapshots) : _snapshot;} + {_user = If( json?.PropertyT("users"), out var __jsonUsers) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Users.FromJson(__jsonUsers) : _user;} + {_security = If( json?.PropertyT("security"), out var __jsonSecurity) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Security.FromJson(__jsonSecurity) : _security;} + {_unifiedAlertingScreenshot = If( json?.PropertyT("unifiedAlertingScreenshots"), out var __jsonUnifiedAlertingScreenshots) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshots.FromJson(__jsonUnifiedAlertingScreenshots) : _unifiedAlertingScreenshot;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._smtp ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._smtp.ToJson(null,serializationMode) : null, "smtp" ,container.Add ); + AddIf( null != this._snapshot ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._snapshot.ToJson(null,serializationMode) : null, "snapshots" ,container.Add ); + AddIf( null != this._user ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._user.ToJson(null,serializationMode) : null, "users" ,container.Add ); + AddIf( null != this._security ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._security.ToJson(null,serializationMode) : null, "security" ,container.Add ); + AddIf( null != this._unifiedAlertingScreenshot ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._unifiedAlertingScreenshot.ToJson(null,serializationMode) : null, "unifiedAlertingScreenshots" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.PowerShell.cs new file mode 100644 index 00000000000..ddcf3364124 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.PowerShell.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + [System.ComponentModel.TypeConverter(typeof(GrafanaIntegrationsTypeConverter))] + public partial class GrafanaIntegrations + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IGrafanaIntegrations DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GrafanaIntegrations(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GrafanaIntegrations(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GrafanaIntegrations(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)this).AzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("AzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)this).AzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal GrafanaIntegrations(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)this).AzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("AzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)this).AzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.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.Dashboard.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(); + } + } + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + [System.ComponentModel.TypeConverter(typeof(GrafanaIntegrationsTypeConverter))] + public partial interface IGrafanaIntegrations + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.TypeConverter.cs new file mode 100644 index 00000000000..6ef1dc650af --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GrafanaIntegrationsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IGrafanaIntegrations ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GrafanaIntegrations.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GrafanaIntegrations.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GrafanaIntegrations.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.cs new file mode 100644 index 00000000000..50dc72d97e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + public partial class GrafanaIntegrations : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _azureMonitorWorkspaceIntegration; + + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List AzureMonitorWorkspaceIntegration { get => this._azureMonitorWorkspaceIntegration; set => this._azureMonitorWorkspaceIntegration = value; } + + /// Creates an new instance. + public GrafanaIntegrations() + { + + } + } + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + public partial interface IGrafanaIntegrations : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + System.Collections.Generic.List AzureMonitorWorkspaceIntegration { get; set; } + + } + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + internal partial interface IGrafanaIntegrationsInternal + + { + /// Array of AzureMonitorWorkspaceIntegration + System.Collections.Generic.List AzureMonitorWorkspaceIntegration { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.json.cs new file mode 100644 index 00000000000..bb8507e4b95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaIntegrations.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + public partial class GrafanaIntegrations + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new GrafanaIntegrations(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal GrafanaIntegrations(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_azureMonitorWorkspaceIntegration = If( json?.PropertyT("azureMonitorWorkspaceIntegrations"), out var __jsonAzureMonitorWorkspaceIntegrations) ? If( __jsonAzureMonitorWorkspaceIntegrations as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IAzureMonitorWorkspaceIntegration) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegration.FromJson(__u) )) ))() : null : _azureMonitorWorkspaceIntegration;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._azureMonitorWorkspaceIntegration) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._azureMonitorWorkspaceIntegration ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("azureMonitorWorkspaceIntegrations",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.PowerShell.cs new file mode 100644 index 00000000000..68cf361f63a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Plugin of Grafana + [System.ComponentModel.TypeConverter(typeof(GrafanaPluginTypeConverter))] + public partial class GrafanaPlugin + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IGrafanaPlugin DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GrafanaPlugin(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GrafanaPlugin(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GrafanaPlugin(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PluginId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPluginInternal)this).PluginId = (string) content.GetValueForProperty("PluginId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPluginInternal)this).PluginId, 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 GrafanaPlugin(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PluginId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPluginInternal)this).PluginId = (string) content.GetValueForProperty("PluginId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPluginInternal)this).PluginId, 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.Dashboard.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(); + } + } + /// Plugin of Grafana + [System.ComponentModel.TypeConverter(typeof(GrafanaPluginTypeConverter))] + public partial interface IGrafanaPlugin + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.TypeConverter.cs new file mode 100644 index 00000000000..5f820818ee6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GrafanaPluginTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IGrafanaPlugin ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GrafanaPlugin.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GrafanaPlugin.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GrafanaPlugin.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.cs new file mode 100644 index 00000000000..93284997b79 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Plugin of Grafana + public partial class GrafanaPlugin : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPluginInternal + { + + /// Internal Acessors for PluginId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPluginInternal.PluginId { get => this._pluginId; set { {_pluginId = value;} } } + + /// Backing field for property. + private string _pluginId; + + /// Grafana plugin id + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PluginId { get => this._pluginId; } + + /// Creates an new instance. + public GrafanaPlugin() + { + + } + } + /// Plugin of Grafana + public partial interface IGrafanaPlugin : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Grafana plugin id + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Grafana plugin id", + SerializedName = @"pluginId", + PossibleTypes = new [] { typeof(string) })] + string PluginId { get; } + + } + /// Plugin of Grafana + internal partial interface IGrafanaPluginInternal + + { + /// Grafana plugin id + string PluginId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.json.cs new file mode 100644 index 00000000000..a6964b18a22 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/GrafanaPlugin.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Plugin of Grafana + public partial class GrafanaPlugin + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new GrafanaPlugin(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal GrafanaPlugin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_pluginId = If( json?.PropertyT("pluginId"), out var __jsonPluginId) ? (string)__jsonPluginId : (string)_pluginId;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._pluginId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._pluginId.ToString()) : null, "pluginId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.PowerShell.cs new file mode 100644 index 00000000000..eb4ed056eeb --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The integration fabric resource type. + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricTypeConverter))] + public partial class IntegrationFabric + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IIntegrationFabric DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IntegrationFabric(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IntegrationFabric(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IntegrationFabric(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.Dashboard.Models.IIntegrationFabricInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).TargetResourceId, global::System.Convert.ToString); + } + if (content.Contains("DataSourceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).DataSourceResourceId = (string) content.GetValueForProperty("DataSourceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).DataSourceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).Scenario, __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 IntegrationFabric(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.Dashboard.Models.IIntegrationFabricInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).TargetResourceId, global::System.Convert.ToString); + } + if (content.Contains("DataSourceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).DataSourceResourceId = (string) content.GetValueForProperty("DataSourceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).DataSourceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal)this).Scenario, __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.Dashboard.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 integration fabric resource type. + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricTypeConverter))] + public partial interface IIntegrationFabric + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.TypeConverter.cs new file mode 100644 index 00000000000..0627778248c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IntegrationFabricTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IIntegrationFabric ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IntegrationFabric.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IntegrationFabric.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IntegrationFabric.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.cs new file mode 100644 index 00000000000..45d41f7f00a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The integration fabric resource type. + public partial class IntegrationFabric : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResource(); + + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DataSourceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).DataSourceResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).DataSourceResourceId = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties _property; + + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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); } + + /// A list of integration scenarios covered by this integration fabric + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Scenario { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).Scenario; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).Scenario = value ?? null /* arrayOf */; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Tag = value ?? null /* model class */; } + + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string TargetResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).TargetResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)Property).TargetResourceId = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public IntegrationFabric() + { + + } + + /// 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.Dashboard.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// The integration fabric resource type. + public partial interface IIntegrationFabric : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource + { + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, an Azure Data Explorer cluster, etc.", + SerializedName = @"dataSourceResourceId", + PossibleTypes = new [] { typeof(string) })] + string DataSourceResourceId { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// A list of integration scenarios covered by this integration fabric + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A list of integration scenarios covered by this integration fabric", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List Scenario { get; set; } + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster.", + SerializedName = @"targetResourceId", + PossibleTypes = new [] { typeof(string) })] + string TargetResourceId { get; set; } + + } + /// The integration fabric resource type. + internal partial interface IIntegrationFabricInternal : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal + { + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + string DataSourceResourceId { get; set; } + + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// A list of integration scenarios covered by this integration fabric + System.Collections.Generic.List Scenario { get; set; } + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + string TargetResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.json.cs new file mode 100644 index 00000000000..870f290310b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabric.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The integration fabric resource type. + public partial class IntegrationFabric + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new IntegrationFabric(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal IntegrationFabric(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricProperties.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.PowerShell.cs new file mode 100644 index 00000000000..d0004a17b6b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Paged collection of IntegrationFabric items + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricListResponseTypeConverter))] + public partial class IntegrationFabricListResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IIntegrationFabricListResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IntegrationFabricListResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IntegrationFabricListResponse(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IntegrationFabricListResponse(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.Dashboard.Models.IIntegrationFabricListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal)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 IntegrationFabricListResponse(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.Dashboard.Models.IIntegrationFabricListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal)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.Dashboard.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 IntegrationFabric items + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricListResponseTypeConverter))] + public partial interface IIntegrationFabricListResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.TypeConverter.cs new file mode 100644 index 00000000000..aec3d79212f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IntegrationFabricListResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IIntegrationFabricListResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IntegrationFabricListResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IntegrationFabricListResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IntegrationFabricListResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.cs new file mode 100644 index 00000000000..90ad7bdb4b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Paged collection of IntegrationFabric items + public partial class IntegrationFabricListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponseInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The IntegrationFabric items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public IntegrationFabricListResponse() + { + + } + } + /// Paged collection of IntegrationFabric items + public partial interface IIntegrationFabricListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 IntegrationFabric items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The IntegrationFabric items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Paged collection of IntegrationFabric items + internal partial interface IIntegrationFabricListResponseInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The IntegrationFabric items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.json.cs new file mode 100644 index 00000000000..8668a251e49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Paged collection of IntegrationFabric items + public partial class IntegrationFabricListResponse + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricListResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new IntegrationFabricListResponse(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal IntegrationFabricListResponse(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.PowerShell.cs new file mode 100644 index 00000000000..8c7f7f76113 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricPropertiesTypeConverter))] + public partial class IntegrationFabricProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IIntegrationFabricProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IntegrationFabricProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IntegrationFabricProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IntegrationFabricProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).TargetResourceId, global::System.Convert.ToString); + } + if (content.Contains("DataSourceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).DataSourceResourceId = (string) content.GetValueForProperty("DataSourceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).DataSourceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).Scenario, __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 IntegrationFabricProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).TargetResourceId, global::System.Convert.ToString); + } + if (content.Contains("DataSourceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).DataSourceResourceId = (string) content.GetValueForProperty("DataSourceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).DataSourceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal)this).Scenario, __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.Dashboard.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(IntegrationFabricPropertiesTypeConverter))] + public partial interface IIntegrationFabricProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.TypeConverter.cs new file mode 100644 index 00000000000..8c756885e31 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IntegrationFabricPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IIntegrationFabricProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IntegrationFabricProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IntegrationFabricProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IntegrationFabricProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.cs new file mode 100644 index 00000000000..0352e396e3e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class IntegrationFabricProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal + { + + /// Backing field for property. + private string _dataSourceResourceId; + + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string DataSourceResourceId { get => this._dataSourceResourceId; set => this._dataSourceResourceId = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private System.Collections.Generic.List _scenario; + + /// A list of integration scenarios covered by this integration fabric + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Scenario { get => this._scenario; set => this._scenario = value; } + + /// Backing field for property. + private string _targetResourceId; + + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string TargetResourceId { get => this._targetResourceId; set => this._targetResourceId = value; } + + /// Creates an new instance. + public IntegrationFabricProperties() + { + + } + } + public partial interface IIntegrationFabricProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, an Azure Data Explorer cluster, etc.", + SerializedName = @"dataSourceResourceId", + PossibleTypes = new [] { typeof(string) })] + string DataSourceResourceId { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// A list of integration scenarios covered by this integration fabric + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A list of integration scenarios covered by this integration fabric", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List Scenario { get; set; } + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster.", + SerializedName = @"targetResourceId", + PossibleTypes = new [] { typeof(string) })] + string TargetResourceId { get; set; } + + } + internal partial interface IIntegrationFabricPropertiesInternal + + { + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + string DataSourceResourceId { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// A list of integration scenarios covered by this integration fabric + System.Collections.Generic.List Scenario { get; set; } + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + string TargetResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.json.cs new file mode 100644 index 00000000000..e893591db34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricProperties.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class IntegrationFabricProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new IntegrationFabricProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal IntegrationFabricProperties(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_targetResourceId = If( json?.PropertyT("targetResourceId"), out var __jsonTargetResourceId) ? (string)__jsonTargetResourceId : (string)_targetResourceId;} + {_dataSourceResourceId = If( json?.PropertyT("dataSourceResourceId"), out var __jsonDataSourceResourceId) ? (string)__jsonDataSourceResourceId : (string)_dataSourceResourceId;} + {_scenario = If( json?.PropertyT("scenarios"), out var __jsonScenarios) ? If( __jsonScenarios as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _scenario;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AddIf( null != (((object)this._targetResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._targetResourceId.ToString()) : null, "targetResourceId" ,container.Add ); + AddIf( null != (((object)this._dataSourceResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._dataSourceResourceId.ToString()) : null, "dataSourceResourceId" ,container.Add ); + if (null != this._scenario) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._scenario ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("scenarios",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.PowerShell.cs new file mode 100644 index 00000000000..0ccf2991825 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The new properties of this Integration Fabric resource + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricPropertiesUpdateParametersTypeConverter))] + public partial class IntegrationFabricPropertiesUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IntegrationFabricPropertiesUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IntegrationFabricPropertiesUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a + /// json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IntegrationFabricPropertiesUpdateParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal)this).Scenario, __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 IntegrationFabricPropertiesUpdateParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal)this).Scenario, __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.Dashboard.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 new properties of this Integration Fabric resource + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricPropertiesUpdateParametersTypeConverter))] + public partial interface IIntegrationFabricPropertiesUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.TypeConverter.cs new file mode 100644 index 00000000000..8a824a393d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IntegrationFabricPropertiesUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IntegrationFabricPropertiesUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IntegrationFabricPropertiesUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IntegrationFabricPropertiesUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.cs new file mode 100644 index 00000000000..7e6d84ec2d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new properties of this Integration Fabric resource + public partial class IntegrationFabricPropertiesUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _scenario; + + /// The new integration scenarios covered by this integration fabric. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Scenario { get => this._scenario; set => this._scenario = value; } + + /// + /// Creates an new instance. + /// + public IntegrationFabricPropertiesUpdateParameters() + { + + } + } + /// The new properties of this Integration Fabric resource + public partial interface IIntegrationFabricPropertiesUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The new integration scenarios covered by this integration fabric. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The new integration scenarios covered by this integration fabric.", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List Scenario { get; set; } + + } + /// The new properties of this Integration Fabric resource + internal partial interface IIntegrationFabricPropertiesUpdateParametersInternal + + { + /// The new integration scenarios covered by this integration fabric. + System.Collections.Generic.List Scenario { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.json.cs new file mode 100644 index 00000000000..b7109de0bb8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricPropertiesUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new properties of this Integration Fabric resource + public partial class IntegrationFabricPropertiesUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new IntegrationFabricPropertiesUpdateParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal IntegrationFabricPropertiesUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_scenario = If( json?.PropertyT("scenarios"), out var __jsonScenarios) ? If( __jsonScenarios as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _scenario;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._scenario) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._scenario ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("scenarios",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.PowerShell.cs new file mode 100644 index 00000000000..cee79296825 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The parameters for a PATCH request to a Integration Fabric resource. + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricUpdateParametersTypeConverter))] + public partial class IntegrationFabricUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IIntegrationFabricUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IntegrationFabricUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IntegrationFabricUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IntegrationFabricUpdateParameters(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.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricPropertiesUpdateParametersTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParametersTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Scenario, __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 IntegrationFabricUpdateParameters(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.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricPropertiesUpdateParametersTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParametersTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Scenario")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Scenario = (System.Collections.Generic.List) content.GetValueForProperty("Scenario",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal)this).Scenario, __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.Dashboard.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 for a PATCH request to a Integration Fabric resource. + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricUpdateParametersTypeConverter))] + public partial interface IIntegrationFabricUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.TypeConverter.cs new file mode 100644 index 00000000000..19c05b9fce8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IntegrationFabricUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IIntegrationFabricUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IntegrationFabricUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IntegrationFabricUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IntegrationFabricUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.cs new file mode 100644 index 00000000000..60810ab6669 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a Integration Fabric resource. + public partial class IntegrationFabricUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal + { + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricPropertiesUpdateParameters()); set { {_property = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters _property; + + /// The new properties of this Integration Fabric resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricPropertiesUpdateParameters()); set => this._property = value; } + + /// The new integration scenarios covered by this integration fabric. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Scenario { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal)Property).Scenario; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParametersInternal)Property).Scenario = value ?? null /* arrayOf */; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags _tag; + + /// The new tags of the Integration Fabric resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParametersTags()); set => this._tag = value; } + + /// Creates an new instance. + public IntegrationFabricUpdateParameters() + { + + } + } + /// The parameters for a PATCH request to a Integration Fabric resource. + public partial interface IIntegrationFabricUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The new integration scenarios covered by this integration fabric. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The new integration scenarios covered by this integration fabric.", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List Scenario { get; set; } + /// The new tags of the Integration Fabric resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The new tags of the Integration Fabric resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags Tag { get; set; } + + } + /// The parameters for a PATCH request to a Integration Fabric resource. + internal partial interface IIntegrationFabricUpdateParametersInternal + + { + /// The new properties of this Integration Fabric resource + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricPropertiesUpdateParameters Property { get; set; } + /// The new integration scenarios covered by this integration fabric. + System.Collections.Generic.List Scenario { get; set; } + /// The new tags of the Integration Fabric resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.json.cs new file mode 100644 index 00000000000..93a3d67d05c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a Integration Fabric resource. + public partial class IntegrationFabricUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new IntegrationFabricUpdateParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal IntegrationFabricUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IntegrationFabricPropertiesUpdateParameters.FromJson(__jsonProperties) : _property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParametersTags.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.PowerShell.cs new file mode 100644 index 00000000000..0e3fcc36e56 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.PowerShell.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The new tags of the Integration Fabric resource. + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricUpdateParametersTagsTypeConverter))] + public partial class IntegrationFabricUpdateParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IIntegrationFabricUpdateParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IntegrationFabricUpdateParametersTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IntegrationFabricUpdateParametersTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IntegrationFabricUpdateParametersTags(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 IntegrationFabricUpdateParametersTags(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.Dashboard.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 new tags of the Integration Fabric resource. + [System.ComponentModel.TypeConverter(typeof(IntegrationFabricUpdateParametersTagsTypeConverter))] + public partial interface IIntegrationFabricUpdateParametersTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.TypeConverter.cs new file mode 100644 index 00000000000..7c461dd6444 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IntegrationFabricUpdateParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IIntegrationFabricUpdateParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IntegrationFabricUpdateParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IntegrationFabricUpdateParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IntegrationFabricUpdateParametersTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.cs new file mode 100644 index 00000000000..8514233a4f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the Integration Fabric resource. + public partial class IntegrationFabricUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTagsInternal + { + + /// Creates an new instance. + public IntegrationFabricUpdateParametersTags() + { + + } + } + /// The new tags of the Integration Fabric resource. + public partial interface IIntegrationFabricUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// The new tags of the Integration Fabric resource. + internal partial interface IIntegrationFabricUpdateParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.dictionary.cs new file mode 100644 index 00000000000..e5059b48ccb --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class IntegrationFabricUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IntegrationFabricUpdateParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.json.cs new file mode 100644 index 00000000000..3d7d12ccc0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/IntegrationFabricUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the Integration Fabric resource. + public partial class IntegrationFabricUpdateParametersTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new IntegrationFabricUpdateParametersTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal IntegrationFabricUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.PowerShell.cs new file mode 100644 index 00000000000..fdc2b3737f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.PowerShell.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The managed dashboard resource type. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardTypeConverter))] + public partial class ManagedDashboard + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedDashboard DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedDashboard(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedDashboard(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedDashboard(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.Dashboard.Models.IManagedDashboardInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal)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 ManagedDashboard(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.Dashboard.Models.IManagedDashboardInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal)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.Dashboard.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 managed dashboard resource type. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardTypeConverter))] + public partial interface IManagedDashboard + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.TypeConverter.cs new file mode 100644 index 00000000000..df527e8f340 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedDashboardTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedDashboard ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedDashboard.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedDashboard.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedDashboard.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.cs new file mode 100644 index 00000000000..18794dd44ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The managed dashboard resource type. + public partial class ManagedDashboard : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties _property; + + /// Properties specific to the managed dashboard resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public ManagedDashboard() + { + + } + + /// 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.Dashboard.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// The managed dashboard resource type. + public partial interface IManagedDashboard : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource + { + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + + } + /// The managed dashboard resource type. + internal partial interface IManagedDashboardInternal : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal + { + /// Properties specific to the managed dashboard resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.json.cs new file mode 100644 index 00000000000..f2280b5c699 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboard.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The managed dashboard resource type. + public partial class ManagedDashboard + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedDashboard(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedDashboard(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardProperties.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.PowerShell.cs new file mode 100644 index 00000000000..020fcb90660 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Paged collection of ManagedDashboard items + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardListResponseTypeConverter))] + public partial class ManagedDashboardListResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedDashboardListResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedDashboardListResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedDashboardListResponse(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedDashboardListResponse(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.Dashboard.Models.IManagedDashboardListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal)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 ManagedDashboardListResponse(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.Dashboard.Models.IManagedDashboardListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal)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.Dashboard.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 ManagedDashboard items + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardListResponseTypeConverter))] + public partial interface IManagedDashboardListResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.TypeConverter.cs new file mode 100644 index 00000000000..6f51a06f896 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedDashboardListResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedDashboardListResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedDashboardListResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedDashboardListResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedDashboardListResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.cs new file mode 100644 index 00000000000..21f06d287a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Paged collection of ManagedDashboard items + public partial class ManagedDashboardListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponseInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The ManagedDashboard items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ManagedDashboardListResponse() + { + + } + } + /// Paged collection of ManagedDashboard items + public partial interface IManagedDashboardListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedDashboard items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ManagedDashboard items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Paged collection of ManagedDashboard items + internal partial interface IManagedDashboardListResponseInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The ManagedDashboard items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.json.cs new file mode 100644 index 00000000000..fc6b15ab1ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Paged collection of ManagedDashboard items + public partial class ManagedDashboardListResponse + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardListResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedDashboardListResponse(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedDashboardListResponse(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.PowerShell.cs new file mode 100644 index 00000000000..3ee8bc8ee40 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Properties specific to the grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardPropertiesTypeConverter))] + public partial class ManagedDashboardProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedDashboardProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedDashboardProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedDashboardProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedDashboardProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)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 ManagedDashboardProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal)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.Dashboard.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 grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardPropertiesTypeConverter))] + public partial interface IManagedDashboardProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.TypeConverter.cs new file mode 100644 index 00000000000..9a84d7eef2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedDashboardPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedDashboardProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedDashboardProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedDashboardProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedDashboardProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.cs new file mode 100644 index 00000000000..dda7d210df2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties specific to the grafana resource. + public partial class ManagedDashboardProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal + { + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Creates an new instance. + public ManagedDashboardProperties() + { + + } + } + /// Properties specific to the grafana resource. + public partial interface IManagedDashboardProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + + } + /// Properties specific to the grafana resource. + internal partial interface IManagedDashboardPropertiesInternal + + { + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.json.cs new file mode 100644 index 00000000000..228940f0e4e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardProperties.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties specific to the grafana resource. + public partial class ManagedDashboardProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedDashboardProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedDashboardProperties(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.PowerShell.cs new file mode 100644 index 00000000000..244278809ce --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The parameters for a PATCH request to a managed dashboard resource. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardUpdateParametersTypeConverter))] + public partial class ManagedDashboardUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedDashboardUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedDashboardUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedDashboardUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedDashboardUpdateParameters(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.Dashboard.Models.IManagedDashboardUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardUpdateParametersTagsTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedDashboardUpdateParameters(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.Dashboard.Models.IManagedDashboardUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardUpdateParametersTagsTypeConverter.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.Dashboard.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 for a PATCH request to a managed dashboard resource. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardUpdateParametersTypeConverter))] + public partial interface IManagedDashboardUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.TypeConverter.cs new file mode 100644 index 00000000000..960dc789337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedDashboardUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedDashboardUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedDashboardUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedDashboardUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedDashboardUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.cs new file mode 100644 index 00000000000..fb1e24eff9b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a managed dashboard resource. + public partial class ManagedDashboardUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags _tag; + + /// The new tags of the managed dashboard resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardUpdateParametersTags()); set => this._tag = value; } + + /// Creates an new instance. + public ManagedDashboardUpdateParameters() + { + + } + } + /// The parameters for a PATCH request to a managed dashboard resource. + public partial interface IManagedDashboardUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The new tags of the managed dashboard resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The new tags of the managed dashboard resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags Tag { get; set; } + + } + /// The parameters for a PATCH request to a managed dashboard resource. + internal partial interface IManagedDashboardUpdateParametersInternal + + { + /// The new tags of the managed dashboard resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.json.cs new file mode 100644 index 00000000000..e1390f1b6c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a managed dashboard resource. + public partial class ManagedDashboardUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedDashboardUpdateParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedDashboardUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardUpdateParametersTags.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.PowerShell.cs new file mode 100644 index 00000000000..17a7795e982 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.PowerShell.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The new tags of the managed dashboard resource. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardUpdateParametersTagsTypeConverter))] + public partial class ManagedDashboardUpdateParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedDashboardUpdateParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedDashboardUpdateParametersTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedDashboardUpdateParametersTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedDashboardUpdateParametersTags(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 ManagedDashboardUpdateParametersTags(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.Dashboard.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 new tags of the managed dashboard resource. + [System.ComponentModel.TypeConverter(typeof(ManagedDashboardUpdateParametersTagsTypeConverter))] + public partial interface IManagedDashboardUpdateParametersTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.TypeConverter.cs new file mode 100644 index 00000000000..0b4e7642f62 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedDashboardUpdateParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedDashboardUpdateParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedDashboardUpdateParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedDashboardUpdateParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedDashboardUpdateParametersTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.cs new file mode 100644 index 00000000000..b98159563c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the managed dashboard resource. + public partial class ManagedDashboardUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTagsInternal + { + + /// Creates an new instance. + public ManagedDashboardUpdateParametersTags() + { + + } + } + /// The new tags of the managed dashboard resource. + public partial interface IManagedDashboardUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// The new tags of the managed dashboard resource. + internal partial interface IManagedDashboardUpdateParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.dictionary.cs new file mode 100644 index 00000000000..3ac61f992e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedDashboardUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.ManagedDashboardUpdateParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.json.cs new file mode 100644 index 00000000000..49ad4b8dbb5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedDashboardUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the managed dashboard resource. + public partial class ManagedDashboardUpdateParametersTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedDashboardUpdateParametersTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedDashboardUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.PowerShell.cs new file mode 100644 index 00000000000..5c7a4102c93 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.PowerShell.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The grafana resource type. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaTypeConverter))] + public partial class ManagedGrafana + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafana DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafana(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafana(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafana(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.Dashboard.Models.IManagedGrafanaInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSkuTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("GrafanaVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaVersion = (string) content.GetValueForProperty("GrafanaVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaVersion, global::System.Convert.ToString); + } + if (content.Contains("Endpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Endpoint, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("OutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).OutboundIP = (System.Collections.Generic.List) content.GetValueForProperty("OutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).OutboundIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("PrivateEndpointConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PrivateEndpointConnection = (System.Collections.Generic.List) content.GetValueForProperty("PrivateEndpointConnection",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PrivateEndpointConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("AutoGeneratedDomainNameLabelScope")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).AutoGeneratedDomainNameLabelScope = (string) content.GetValueForProperty("AutoGeneratedDomainNameLabelScope",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).AutoGeneratedDomainNameLabelScope, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SkuName, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedGrafana(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.Dashboard.Models.IManagedGrafanaInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSkuTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("GrafanaVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaVersion = (string) content.GetValueForProperty("GrafanaVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaVersion, global::System.Convert.ToString); + } + if (content.Contains("Endpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).Endpoint, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("OutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).OutboundIP = (System.Collections.Generic.List) content.GetValueForProperty("OutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).OutboundIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("PrivateEndpointConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PrivateEndpointConnection = (System.Collections.Generic.List) content.GetValueForProperty("PrivateEndpointConnection",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).PrivateEndpointConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("AutoGeneratedDomainNameLabelScope")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).AutoGeneratedDomainNameLabelScope = (string) content.GetValueForProperty("AutoGeneratedDomainNameLabelScope",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).AutoGeneratedDomainNameLabelScope, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SkuName, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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 grafana resource type. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaTypeConverter))] + public partial interface IManagedGrafana + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.TypeConverter.cs new file mode 100644 index 00000000000..25e3cff121b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafana ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafana.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafana.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafana.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.cs new file mode 100644 index 00000000000..856ad90523d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.cs @@ -0,0 +1,943 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The grafana resource type. + public partial class ManagedGrafana : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ProxyResource(); + + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ApiKey { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ApiKey; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ApiKey = value ?? null; } + + /// Scope for dns deterministic name hash calculation. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string AutoGeneratedDomainNameLabelScope { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).AutoGeneratedDomainNameLabelScope; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).AutoGeneratedDomainNameLabelScope = value ?? null; } + + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DeterministicOutboundIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).DeterministicOutboundIP; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).DeterministicOutboundIP = value ?? null; } + + /// The endpoint of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string Endpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).Endpoint; } + + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).EnterpriseConfigurationMarketplaceAutoRenew; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).EnterpriseConfigurationMarketplaceAutoRenew = value ?? null; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplacePlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).EnterpriseConfigurationMarketplacePlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).EnterpriseConfigurationMarketplacePlanId = value ?? null; } + + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaIntegrationAzureMonitorWorkspaceIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaIntegrationAzureMonitorWorkspaceIntegration = value ?? null /* arrayOf */; } + + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string GrafanaMajorVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaMajorVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaMajorVersion = value ?? null; } + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaPlugin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaPlugin = value ?? null /* model class */; } + + /// The Grafana software version. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string GrafanaVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaVersion; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Endpoint + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.Endpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).Endpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).Endpoint = value ?? null; } + + /// Internal Acessors for EnterpriseConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.EnterpriseConfiguration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).EnterpriseConfiguration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).EnterpriseConfiguration = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaConfiguration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfiguration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfiguration = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSecurity + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaConfigurationSecurity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationSecurity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationSecurity = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSmtp + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaConfigurationSmtp { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationSmtp; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationSmtp = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSnapshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaConfigurationSnapshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationSnapshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationSnapshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUnifiedAlertingScreenshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaConfigurationUnifiedAlertingScreenshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationUnifiedAlertingScreenshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationUnifiedAlertingScreenshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUser + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaConfigurationUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationUser; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaConfigurationUser = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaIntegration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaIntegration = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaVersion + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.GrafanaVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).GrafanaVersion = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Internal Acessors for OutboundIP + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.OutboundIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).OutboundIP; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).OutboundIP = value ?? null /* arrayOf */; } + + /// Internal Acessors for PrivateEndpointConnection + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.PrivateEndpointConnection { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).PrivateEndpointConnection; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).PrivateEndpointConnection = value ?? null /* arrayOf */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSku()); set { {_sku = value;} } } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name; } + + /// List of outbound IPs if deterministicOutboundIP is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List OutboundIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).OutboundIP; } + + /// The private endpoint connections of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List PrivateEndpointConnection { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).PrivateEndpointConnection; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties _property; + + /// Properties specific to the grafana resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ProvisioningState; } + + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PublicNetworkAccess { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).PublicNetworkAccess; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).PublicNetworkAccess = value ?? null; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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); } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SecurityCsrfAlwaysCheck { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SecurityCsrfAlwaysCheck; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SecurityCsrfAlwaysCheck = value ?? default(bool); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku _sku; + + /// The Sku of the grafana resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSku()); set => this._sku = value; } + + /// The name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal)Sku).Name = value ?? null; } + + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpEnabled = value ?? default(bool); } + + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpFromAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpFromAddress = value ?? null; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpFromName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpFromName = value ?? null; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpHost { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpHost; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpHost = value ?? null; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Security.SecureString SmtpPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpPassword; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpPassword = value ?? null; } + + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpSkipVerify { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpSkipVerify; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpSkipVerify = value ?? default(bool); } + + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpStartTlsPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpStartTlsPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpStartTlsPolicy = value ?? null; } + + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpUser; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SmtpUser = value ?? null; } + + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SnapshotExternalEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SnapshotExternalEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).SnapshotExternalEnabled = value ?? default(bool); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaTags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type; } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UnifiedAlertingScreenshotCaptureEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).UnifiedAlertingScreenshotCaptureEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).UnifiedAlertingScreenshotCaptureEnabled = value ?? default(bool); } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserEditorsCanAdmin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).UserEditorsCanAdmin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).UserEditorsCanAdmin = value ?? default(bool); } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserViewersCanEdit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).UserViewersCanEdit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).UserViewersCanEdit = value ?? default(bool); } + + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ZoneRedundancy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ZoneRedundancy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)Property).ZoneRedundancy = value ?? null; } + + /// Creates an new instance. + public ManagedGrafana() + { + + } + + /// 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.Dashboard.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// The grafana resource type. + public partial interface IManagedGrafana : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource + { + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Scope for dns deterministic name hash calculation. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Scope for dns deterministic name hash calculation.", + SerializedName = @"autoGeneratedDomainNameLabelScope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("TenantReuse")] + string AutoGeneratedDomainNameLabelScope { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// The endpoint of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The endpoint of the Grafana instance.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + string Endpoint { get; } + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + string GrafanaMajorVersion { get; set; } + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get; set; } + /// The Grafana software version. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Grafana software version.", + SerializedName = @"grafanaVersion", + PossibleTypes = new [] { typeof(string) })] + string GrafanaVersion { get; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + 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; } + /// List of outbound IPs if deterministicOutboundIP is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of outbound IPs if deterministicOutboundIP is enabled.", + SerializedName = @"outboundIPs", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List OutboundIP { get; } + /// The private endpoint connections of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private endpoint connections of the Grafana instance.", + SerializedName = @"privateEndpointConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection) })] + System.Collections.Generic.List PrivateEndpointConnection { get; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(bool) })] + bool? SecurityCsrfAlwaysCheck { get; set; } + /// The name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string SkuName { get; set; } + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Address used when sending out emails + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification"" + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Verify SSL for SMTP server. Default is false + https://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The StartTLSPolicy setting of the SMTP configuration + https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SnapshotExternalEnabled { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags Tag { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(bool) })] + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(bool) })] + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } + /// The grafana resource type. + internal partial interface IManagedGrafanaInternal : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResourceInternal + { + /// The api key setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Scope for dns deterministic name hash calculation. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("TenantReuse")] + string AutoGeneratedDomainNameLabelScope { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// The endpoint of the Grafana instance. + string Endpoint { get; set; } + /// Enterprise settings of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations EnterpriseConfiguration { get; set; } + /// The AutoRenew setting of the Enterprise subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Server configurations of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations GrafanaConfiguration { get; set; } + /// Grafana security settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity GrafanaConfigurationSecurity { get; set; } + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp GrafanaConfigurationSmtp { get; set; } + /// Grafana Snapshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots GrafanaConfigurationSnapshot { get; set; } + /// Grafana Unified Alerting Screenshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots GrafanaConfigurationUnifiedAlertingScreenshot { get; set; } + /// Grafana users settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers GrafanaConfigurationUser { get; set; } + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations GrafanaIntegration { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + string GrafanaMajorVersion { get; set; } + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get; set; } + /// The Grafana software version. + string GrafanaVersion { get; set; } + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// The geo-location where the resource lives + string Location { get; set; } + /// List of outbound IPs if deterministicOutboundIP is enabled. + System.Collections.Generic.List OutboundIP { get; set; } + /// The private endpoint connections of the Grafana instance. + System.Collections.Generic.List PrivateEndpointConnection { get; set; } + /// Properties specific to the grafana resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// Indicate the state for enable or disable traffic over the public interface. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + bool? SecurityCsrfAlwaysCheck { get; set; } + /// The Sku of the grafana resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku Sku { get; set; } + /// The name of the SKU. + string SkuName { get; set; } + /// Enable this to allow Grafana to send email. Default is false + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + bool? SnapshotExternalEnabled { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags Tag { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.json.cs new file mode 100644 index 00000000000..da751f20e4f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafana.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The grafana resource type. + public partial class ManagedGrafana + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafana(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedGrafana(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaProperties.FromJson(__jsonProperties) : _property;} + {_sku = If( json?.PropertyT("sku"), out var __jsonSku) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSku.FromJson(__jsonSku) : _sku;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaTags.FromJson(__jsonTags) : _tag;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.PowerShell.cs new file mode 100644 index 00000000000..b0013c94f64 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Paged collection of ManagedGrafana items + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaListResponseTypeConverter))] + public partial class ManagedGrafanaListResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaListResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaListResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaListResponse(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaListResponse(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.Dashboard.Models.IManagedGrafanaListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal)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 ManagedGrafanaListResponse(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.Dashboard.Models.IManagedGrafanaListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal)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.Dashboard.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 ManagedGrafana items + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaListResponseTypeConverter))] + public partial interface IManagedGrafanaListResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.TypeConverter.cs new file mode 100644 index 00000000000..ea0ec2a2f70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaListResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaListResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaListResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaListResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaListResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.cs new file mode 100644 index 00000000000..0b134aa0855 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Paged collection of ManagedGrafana items + public partial class ManagedGrafanaListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponseInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The ManagedGrafana items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ManagedGrafanaListResponse() + { + + } + } + /// Paged collection of ManagedGrafana items + public partial interface IManagedGrafanaListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedGrafana items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ManagedGrafana items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Paged collection of ManagedGrafana items + internal partial interface IManagedGrafanaListResponseInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The ManagedGrafana items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.json.cs new file mode 100644 index 00000000000..5cb5126c17e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Paged collection of ManagedGrafana items + public partial class ManagedGrafanaListResponse + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaListResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaListResponse(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedGrafanaListResponse(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.PowerShell.cs new file mode 100644 index 00000000000..3803203fdc8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Properties specific to the grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesTypeConverter))] + public partial class ManagedGrafanaProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GrafanaVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaVersion = (string) content.GetValueForProperty("GrafanaVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaVersion, global::System.Convert.ToString); + } + if (content.Contains("Endpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).Endpoint, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("OutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).OutboundIP = (System.Collections.Generic.List) content.GetValueForProperty("OutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).OutboundIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("PrivateEndpointConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PrivateEndpointConnection = (System.Collections.Generic.List) content.GetValueForProperty("PrivateEndpointConnection",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PrivateEndpointConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("AutoGeneratedDomainNameLabelScope")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).AutoGeneratedDomainNameLabelScope = (string) content.GetValueForProperty("AutoGeneratedDomainNameLabelScope",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).AutoGeneratedDomainNameLabelScope, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedGrafanaProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GrafanaVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaVersion = (string) content.GetValueForProperty("GrafanaVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaVersion, global::System.Convert.ToString); + } + if (content.Contains("Endpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).Endpoint, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("OutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).OutboundIP = (System.Collections.Generic.List) content.GetValueForProperty("OutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).OutboundIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("PrivateEndpointConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PrivateEndpointConnection = (System.Collections.Generic.List) content.GetValueForProperty("PrivateEndpointConnection",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).PrivateEndpointConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("AutoGeneratedDomainNameLabelScope")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).AutoGeneratedDomainNameLabelScope = (string) content.GetValueForProperty("AutoGeneratedDomainNameLabelScope",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).AutoGeneratedDomainNameLabelScope, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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 grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesTypeConverter))] + public partial interface IManagedGrafanaProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.TypeConverter.cs new file mode 100644 index 00000000000..7ba72ab2323 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.cs new file mode 100644 index 00000000000..cfafdff621e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties specific to the grafana resource. + public partial class ManagedGrafanaProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal + { + + /// Backing field for property. + private string _apiKey; + + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ApiKey { get => this._apiKey; set => this._apiKey = value; } + + /// Backing field for property. + private string _autoGeneratedDomainNameLabelScope; + + /// Scope for dns deterministic name hash calculation. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string AutoGeneratedDomainNameLabelScope { get => this._autoGeneratedDomainNameLabelScope; set => this._autoGeneratedDomainNameLabelScope = value; } + + /// Backing field for property. + private string _deterministicOutboundIP; + + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string DeterministicOutboundIP { get => this._deterministicOutboundIP; set => this._deterministicOutboundIP = value; } + + /// Backing field for property. + private string _endpoint; + + /// The endpoint of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Endpoint { get => this._endpoint; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations _enterpriseConfiguration; + + /// Enterprise settings of a Grafana instance + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations EnterpriseConfiguration { get => (this._enterpriseConfiguration = this._enterpriseConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurations()); set => this._enterpriseConfiguration = value; } + + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplaceAutoRenew; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplaceAutoRenew = value ?? null; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplacePlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplacePlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplacePlanId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations _grafanaConfiguration; + + /// Server configurations of a Grafana instance + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations GrafanaConfiguration { get => (this._grafanaConfiguration = this._grafanaConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurations()); set => this._grafanaConfiguration = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations _grafanaIntegration; + + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations GrafanaIntegration { get => (this._grafanaIntegration = this._grafanaIntegration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrations()); set => this._grafanaIntegration = value; } + + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)GrafanaIntegration).AzureMonitorWorkspaceIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)GrafanaIntegration).AzureMonitorWorkspaceIntegration = value ?? null /* arrayOf */; } + + /// Backing field for property. + private string _grafanaMajorVersion; + + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string GrafanaMajorVersion { get => this._grafanaMajorVersion; set => this._grafanaMajorVersion = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins _grafanaPlugin; + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get => (this._grafanaPlugin = this._grafanaPlugin ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPlugins()); set => this._grafanaPlugin = value; } + + /// Backing field for property. + private string _grafanaVersion; + + /// The Grafana software version. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string GrafanaVersion { get => this._grafanaVersion; } + + /// Internal Acessors for Endpoint + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.Endpoint { get => this._endpoint; set { {_endpoint = value;} } } + + /// Internal Acessors for EnterpriseConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.EnterpriseConfiguration { get => (this._enterpriseConfiguration = this._enterpriseConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurations()); set { {_enterpriseConfiguration = value;} } } + + /// Internal Acessors for GrafanaConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaConfiguration { get => (this._grafanaConfiguration = this._grafanaConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurations()); set { {_grafanaConfiguration = value;} } } + + /// Internal Acessors for GrafanaConfigurationSecurity + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaConfigurationSecurity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Security; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Security = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSmtp + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaConfigurationSmtp { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Smtp; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Smtp = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSnapshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaConfigurationSnapshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Snapshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Snapshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUnifiedAlertingScreenshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaConfigurationUnifiedAlertingScreenshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUser + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaConfigurationUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).User; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).User = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaIntegration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaIntegration { get => (this._grafanaIntegration = this._grafanaIntegration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrations()); set { {_grafanaIntegration = value;} } } + + /// Internal Acessors for GrafanaVersion + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.GrafanaVersion { get => this._grafanaVersion; set { {_grafanaVersion = value;} } } + + /// Internal Acessors for OutboundIP + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.OutboundIP { get => this._outboundIP; set { {_outboundIP = value;} } } + + /// Internal Acessors for PrivateEndpointConnection + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.PrivateEndpointConnection { get => this._privateEndpointConnection; set { {_privateEndpointConnection = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _outboundIP; + + /// List of outbound IPs if deterministicOutboundIP is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List OutboundIP { get => this._outboundIP; } + + /// Backing field for property. + private System.Collections.Generic.List _privateEndpointConnection; + + /// The private endpoint connections of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List PrivateEndpointConnection { get => this._privateEndpointConnection; } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _publicNetworkAccess; + + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PublicNetworkAccess { get => this._publicNetworkAccess; set => this._publicNetworkAccess = value; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SecurityCsrfAlwaysCheck { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SecurityCsrfAlwaysCheck; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SecurityCsrfAlwaysCheck = value ?? default(bool); } + + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpEnabled = value ?? default(bool); } + + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromAddress = value ?? null; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromName = value ?? null; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpHost { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpHost; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpHost = value ?? null; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Security.SecureString SmtpPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpPassword; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpPassword = value ?? null; } + + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpSkipVerify { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpSkipVerify; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpSkipVerify = value ?? default(bool); } + + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpStartTlsPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpStartTlsPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpStartTlsPolicy = value ?? null; } + + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpUser; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpUser = value ?? null; } + + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SnapshotExternalEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SnapshotExternalEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SnapshotExternalEnabled = value ?? default(bool); } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UnifiedAlertingScreenshotCaptureEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshotCaptureEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshotCaptureEnabled = value ?? default(bool); } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserEditorsCanAdmin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserEditorsCanAdmin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserEditorsCanAdmin = value ?? default(bool); } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserViewersCanEdit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserViewersCanEdit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserViewersCanEdit = value ?? default(bool); } + + /// Backing field for property. + private string _zoneRedundancy; + + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ZoneRedundancy { get => this._zoneRedundancy; set => this._zoneRedundancy = value; } + + /// Creates an new instance. + public ManagedGrafanaProperties() + { + + } + } + /// Properties specific to the grafana resource. + public partial interface IManagedGrafanaProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Scope for dns deterministic name hash calculation. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Scope for dns deterministic name hash calculation.", + SerializedName = @"autoGeneratedDomainNameLabelScope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("TenantReuse")] + string AutoGeneratedDomainNameLabelScope { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// The endpoint of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The endpoint of the Grafana instance.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + string Endpoint { get; } + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + string GrafanaMajorVersion { get; set; } + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get; set; } + /// The Grafana software version. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Grafana software version.", + SerializedName = @"grafanaVersion", + PossibleTypes = new [] { typeof(string) })] + string GrafanaVersion { get; } + /// List of outbound IPs if deterministicOutboundIP is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of outbound IPs if deterministicOutboundIP is enabled.", + SerializedName = @"outboundIPs", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List OutboundIP { get; } + /// The private endpoint connections of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private endpoint connections of the Grafana instance.", + SerializedName = @"privateEndpointConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection) })] + System.Collections.Generic.List PrivateEndpointConnection { get; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(bool) })] + bool? SecurityCsrfAlwaysCheck { get; set; } + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Address used when sending out emails + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification"" + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Verify SSL for SMTP server. Default is false + https://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The StartTLSPolicy setting of the SMTP configuration + https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SnapshotExternalEnabled { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(bool) })] + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(bool) })] + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } + /// Properties specific to the grafana resource. + internal partial interface IManagedGrafanaPropertiesInternal + + { + /// The api key setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Scope for dns deterministic name hash calculation. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("TenantReuse")] + string AutoGeneratedDomainNameLabelScope { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// The endpoint of the Grafana instance. + string Endpoint { get; set; } + /// Enterprise settings of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations EnterpriseConfiguration { get; set; } + /// The AutoRenew setting of the Enterprise subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Server configurations of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations GrafanaConfiguration { get; set; } + /// Grafana security settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity GrafanaConfigurationSecurity { get; set; } + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp GrafanaConfigurationSmtp { get; set; } + /// Grafana Snapshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots GrafanaConfigurationSnapshot { get; set; } + /// Grafana Unified Alerting Screenshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots GrafanaConfigurationUnifiedAlertingScreenshot { get; set; } + /// Grafana users settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers GrafanaConfigurationUser { get; set; } + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations GrafanaIntegration { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + string GrafanaMajorVersion { get; set; } + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get; set; } + /// The Grafana software version. + string GrafanaVersion { get; set; } + /// List of outbound IPs if deterministicOutboundIP is enabled. + System.Collections.Generic.List OutboundIP { get; set; } + /// The private endpoint connections of the Grafana instance. + System.Collections.Generic.List PrivateEndpointConnection { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// Indicate the state for enable or disable traffic over the public interface. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + bool? SecurityCsrfAlwaysCheck { get; set; } + /// Enable this to allow Grafana to send email. Default is false + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + bool? SnapshotExternalEnabled { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.json.cs new file mode 100644 index 00000000000..e45070b2090 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaProperties.json.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties specific to the grafana resource. + public partial class ManagedGrafanaProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedGrafanaProperties(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_grafanaIntegration = If( json?.PropertyT("grafanaIntegrations"), out var __jsonGrafanaIntegrations) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrations.FromJson(__jsonGrafanaIntegrations) : _grafanaIntegration;} + {_enterpriseConfiguration = If( json?.PropertyT("enterpriseConfigurations"), out var __jsonEnterpriseConfigurations) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurations.FromJson(__jsonEnterpriseConfigurations) : _enterpriseConfiguration;} + {_grafanaConfiguration = If( json?.PropertyT("grafanaConfigurations"), out var __jsonGrafanaConfigurations) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurations.FromJson(__jsonGrafanaConfigurations) : _grafanaConfiguration;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_grafanaVersion = If( json?.PropertyT("grafanaVersion"), out var __jsonGrafanaVersion) ? (string)__jsonGrafanaVersion : (string)_grafanaVersion;} + {_endpoint = If( json?.PropertyT("endpoint"), out var __jsonEndpoint) ? (string)__jsonEndpoint : (string)_endpoint;} + {_publicNetworkAccess = If( json?.PropertyT("publicNetworkAccess"), out var __jsonPublicNetworkAccess) ? (string)__jsonPublicNetworkAccess : (string)_publicNetworkAccess;} + {_zoneRedundancy = If( json?.PropertyT("zoneRedundancy"), out var __jsonZoneRedundancy) ? (string)__jsonZoneRedundancy : (string)_zoneRedundancy;} + {_apiKey = If( json?.PropertyT("apiKey"), out var __jsonApiKey) ? (string)__jsonApiKey : (string)_apiKey;} + {_deterministicOutboundIP = If( json?.PropertyT("deterministicOutboundIP"), out var __jsonDeterministicOutboundIP) ? (string)__jsonDeterministicOutboundIP : (string)_deterministicOutboundIP;} + {_outboundIP = If( json?.PropertyT("outboundIPs"), out var __jsonOutboundIPs) ? If( __jsonOutboundIPs as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _outboundIP;} + {_privateEndpointConnection = If( json?.PropertyT("privateEndpointConnections"), out var __jsonPrivateEndpointConnections) ? If( __jsonPrivateEndpointConnections as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IPrivateEndpointConnection) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnection.FromJson(__p) )) ))() : null : _privateEndpointConnection;} + {_autoGeneratedDomainNameLabelScope = If( json?.PropertyT("autoGeneratedDomainNameLabelScope"), out var __jsonAutoGeneratedDomainNameLabelScope) ? (string)__jsonAutoGeneratedDomainNameLabelScope : (string)_autoGeneratedDomainNameLabelScope;} + {_grafanaPlugin = If( json?.PropertyT("grafanaPlugins"), out var __jsonGrafanaPlugins) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPlugins.FromJson(__jsonGrafanaPlugins) : _grafanaPlugin;} + {_grafanaMajorVersion = If( json?.PropertyT("grafanaMajorVersion"), out var __jsonGrafanaMajorVersion) ? (string)__jsonGrafanaMajorVersion : (string)_grafanaMajorVersion;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._grafanaIntegration ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._grafanaIntegration.ToJson(null,serializationMode) : null, "grafanaIntegrations" ,container.Add ); + AddIf( null != this._enterpriseConfiguration ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._enterpriseConfiguration.ToJson(null,serializationMode) : null, "enterpriseConfigurations" ,container.Add ); + AddIf( null != this._grafanaConfiguration ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._grafanaConfiguration.ToJson(null,serializationMode) : null, "grafanaConfigurations" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._grafanaVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._grafanaVersion.ToString()) : null, "grafanaVersion" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._endpoint)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._endpoint.ToString()) : null, "endpoint" ,container.Add ); + } + AddIf( null != (((object)this._publicNetworkAccess)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._publicNetworkAccess.ToString()) : null, "publicNetworkAccess" ,container.Add ); + AddIf( null != (((object)this._zoneRedundancy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._zoneRedundancy.ToString()) : null, "zoneRedundancy" ,container.Add ); + AddIf( null != (((object)this._apiKey)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._apiKey.ToString()) : null, "apiKey" ,container.Add ); + AddIf( null != (((object)this._deterministicOutboundIP)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._deterministicOutboundIP.ToString()) : null, "deterministicOutboundIP" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._outboundIP) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._outboundIP ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("outboundIPs",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._privateEndpointConnection) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __s in this._privateEndpointConnection ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("privateEndpointConnections",__r); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._autoGeneratedDomainNameLabelScope)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._autoGeneratedDomainNameLabelScope.ToString()) : null, "autoGeneratedDomainNameLabelScope" ,container.Add ); + } + AddIf( null != this._grafanaPlugin ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._grafanaPlugin.ToJson(null,serializationMode) : null, "grafanaPlugins" ,container.Add ); + AddIf( null != (((object)this._grafanaMajorVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._grafanaMajorVersion.ToString()) : null, "grafanaMajorVersion" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.PowerShell.cs new file mode 100644 index 00000000000..c01dc7d2093 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.PowerShell.cs @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesGrafanaPluginsTypeConverter))] + public partial class ManagedGrafanaPropertiesGrafanaPlugins + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaPropertiesGrafanaPlugins(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaPropertiesGrafanaPlugins(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaPropertiesGrafanaPlugins(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 ManagedGrafanaPropertiesGrafanaPlugins(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.Dashboard.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(); + } + } + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesGrafanaPluginsTypeConverter))] + public partial interface IManagedGrafanaPropertiesGrafanaPlugins + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.TypeConverter.cs new file mode 100644 index 00000000000..74ddf11aa5c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaPropertiesGrafanaPluginsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaPropertiesGrafanaPlugins.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaPropertiesGrafanaPlugins.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaPropertiesGrafanaPlugins.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.cs new file mode 100644 index 00000000000..bcc7a7586bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + public partial class ManagedGrafanaPropertiesGrafanaPlugins : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPluginsInternal + { + + /// Creates an new instance. + public ManagedGrafanaPropertiesGrafanaPlugins() + { + + } + } + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + public partial interface IManagedGrafanaPropertiesGrafanaPlugins : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + internal partial interface IManagedGrafanaPropertiesGrafanaPluginsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.dictionary.cs new file mode 100644 index 00000000000..f8f5f10e816 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedGrafanaPropertiesGrafanaPlugins : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin 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.Dashboard.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.Dashboard.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.Dashboard.Models.IGrafanaPlugin value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesGrafanaPlugins source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.json.cs new file mode 100644 index 00000000000..3c336837c09 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesGrafanaPlugins.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + public partial class ManagedGrafanaPropertiesGrafanaPlugins + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaPropertiesGrafanaPlugins(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedGrafanaPropertiesGrafanaPlugins(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaPlugin.FromJson(j) ,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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.PowerShell.cs new file mode 100644 index 00000000000..f41618d7162 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.PowerShell.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The properties parameters for a PATCH request to a grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesUpdateParametersTypeConverter))] + public partial class ManagedGrafanaPropertiesUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaPropertiesUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaPropertiesUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaPropertiesUpdateParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedGrafanaPropertiesUpdateParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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 properties parameters for a PATCH request to a grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesUpdateParametersTypeConverter))] + public partial interface IManagedGrafanaPropertiesUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.TypeConverter.cs new file mode 100644 index 00000000000..b99f66866f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaPropertiesUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaPropertiesUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaPropertiesUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaPropertiesUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.cs new file mode 100644 index 00000000000..7695dad6fd4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The properties parameters for a PATCH request to a grafana resource. + public partial class ManagedGrafanaPropertiesUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal + { + + /// Backing field for property. + private string _apiKey; + + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ApiKey { get => this._apiKey; set => this._apiKey = value; } + + /// Backing field for property. + private string _deterministicOutboundIP; + + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string DeterministicOutboundIP { get => this._deterministicOutboundIP; set => this._deterministicOutboundIP = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations _enterpriseConfiguration; + + /// Enterprise settings of a Grafana instance + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations EnterpriseConfiguration { get => (this._enterpriseConfiguration = this._enterpriseConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurations()); set => this._enterpriseConfiguration = value; } + + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplaceAutoRenew; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplaceAutoRenew = value ?? null; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplacePlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplacePlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurationsInternal)EnterpriseConfiguration).MarketplacePlanId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations _grafanaConfiguration; + + /// Server configurations of a Grafana instance + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations GrafanaConfiguration { get => (this._grafanaConfiguration = this._grafanaConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurations()); set => this._grafanaConfiguration = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations _grafanaIntegration; + + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations GrafanaIntegration { get => (this._grafanaIntegration = this._grafanaIntegration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrations()); set => this._grafanaIntegration = value; } + + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)GrafanaIntegration).AzureMonitorWorkspaceIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrationsInternal)GrafanaIntegration).AzureMonitorWorkspaceIntegration = value ?? null /* arrayOf */; } + + /// Backing field for property. + private string _grafanaMajorVersion; + + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string GrafanaMajorVersion { get => this._grafanaMajorVersion; set => this._grafanaMajorVersion = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins _grafanaPlugin; + + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins GrafanaPlugin { get => (this._grafanaPlugin = this._grafanaPlugin ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins()); set => this._grafanaPlugin = value; } + + /// Internal Acessors for EnterpriseConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.EnterpriseConfiguration { get => (this._enterpriseConfiguration = this._enterpriseConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurations()); set { {_enterpriseConfiguration = value;} } } + + /// Internal Acessors for GrafanaConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaConfiguration { get => (this._grafanaConfiguration = this._grafanaConfiguration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurations()); set { {_grafanaConfiguration = value;} } } + + /// Internal Acessors for GrafanaConfigurationSecurity + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaConfigurationSecurity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Security; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Security = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSmtp + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaConfigurationSmtp { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Smtp; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Smtp = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSnapshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaConfigurationSnapshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Snapshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).Snapshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUnifiedAlertingScreenshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaConfigurationUnifiedAlertingScreenshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUser + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaConfigurationUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).User; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).User = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaIntegration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal.GrafanaIntegration { get => (this._grafanaIntegration = this._grafanaIntegration ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrations()); set { {_grafanaIntegration = value;} } } + + /// Backing field for property. + private string _publicNetworkAccess; + + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PublicNetworkAccess { get => this._publicNetworkAccess; set => this._publicNetworkAccess = value; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SecurityCsrfAlwaysCheck { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SecurityCsrfAlwaysCheck; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SecurityCsrfAlwaysCheck = value ?? default(bool); } + + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpEnabled = value ?? default(bool); } + + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromAddress = value ?? null; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpFromName = value ?? null; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpHost { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpHost; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpHost = value ?? null; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Security.SecureString SmtpPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpPassword; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpPassword = value ?? null; } + + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpSkipVerify { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpSkipVerify; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpSkipVerify = value ?? default(bool); } + + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpStartTlsPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpStartTlsPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpStartTlsPolicy = value ?? null; } + + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpUser; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SmtpUser = value ?? null; } + + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SnapshotExternalEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SnapshotExternalEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).SnapshotExternalEnabled = value ?? default(bool); } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UnifiedAlertingScreenshotCaptureEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshotCaptureEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UnifiedAlertingScreenshotCaptureEnabled = value ?? default(bool); } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserEditorsCanAdmin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserEditorsCanAdmin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserEditorsCanAdmin = value ?? default(bool); } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserViewersCanEdit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserViewersCanEdit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurationsInternal)GrafanaConfiguration).UserViewersCanEdit = value ?? default(bool); } + + /// Backing field for property. + private string _zoneRedundancy; + + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ZoneRedundancy { get => this._zoneRedundancy; set => this._zoneRedundancy = value; } + + /// + /// Creates an new instance. + /// + public ManagedGrafanaPropertiesUpdateParameters() + { + + } + } + /// The properties parameters for a PATCH request to a grafana resource. + public partial interface IManagedGrafanaPropertiesUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + string GrafanaMajorVersion { get; set; } + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given plugin id will be removed. Otherwise, given plugin will be installed.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins GrafanaPlugin { get; set; } + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(bool) })] + bool? SecurityCsrfAlwaysCheck { get; set; } + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Address used when sending out emails + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification"" + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Verify SSL for SMTP server. Default is false + https://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The StartTLSPolicy setting of the SMTP configuration + https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SnapshotExternalEnabled { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(bool) })] + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(bool) })] + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } + /// The properties parameters for a PATCH request to a grafana resource. + internal partial interface IManagedGrafanaPropertiesUpdateParametersInternal + + { + /// The api key setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// Enterprise settings of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations EnterpriseConfiguration { get; set; } + /// The AutoRenew setting of the Enterprise subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Server configurations of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations GrafanaConfiguration { get; set; } + /// Grafana security settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity GrafanaConfigurationSecurity { get; set; } + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp GrafanaConfigurationSmtp { get; set; } + /// Grafana Snapshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots GrafanaConfigurationSnapshot { get; set; } + /// Grafana Unified Alerting Screenshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots GrafanaConfigurationUnifiedAlertingScreenshot { get; set; } + /// Grafana users settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers GrafanaConfigurationUser { get; set; } + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations GrafanaIntegration { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + string GrafanaMajorVersion { get; set; } + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins GrafanaPlugin { get; set; } + /// Indicate the state for enable or disable traffic over the public interface. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + bool? SecurityCsrfAlwaysCheck { get; set; } + /// Enable this to allow Grafana to send email. Default is false + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + bool? SnapshotExternalEnabled { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.json.cs new file mode 100644 index 00000000000..018c7c94af3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The properties parameters for a PATCH request to a grafana resource. + public partial class ManagedGrafanaPropertiesUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaPropertiesUpdateParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedGrafanaPropertiesUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_grafanaIntegration = If( json?.PropertyT("grafanaIntegrations"), out var __jsonGrafanaIntegrations) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrations.FromJson(__jsonGrafanaIntegrations) : _grafanaIntegration;} + {_enterpriseConfiguration = If( json?.PropertyT("enterpriseConfigurations"), out var __jsonEnterpriseConfigurations) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurations.FromJson(__jsonEnterpriseConfigurations) : _enterpriseConfiguration;} + {_grafanaConfiguration = If( json?.PropertyT("grafanaConfigurations"), out var __jsonGrafanaConfigurations) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurations.FromJson(__jsonGrafanaConfigurations) : _grafanaConfiguration;} + {_zoneRedundancy = If( json?.PropertyT("zoneRedundancy"), out var __jsonZoneRedundancy) ? (string)__jsonZoneRedundancy : (string)_zoneRedundancy;} + {_apiKey = If( json?.PropertyT("apiKey"), out var __jsonApiKey) ? (string)__jsonApiKey : (string)_apiKey;} + {_deterministicOutboundIP = If( json?.PropertyT("deterministicOutboundIP"), out var __jsonDeterministicOutboundIP) ? (string)__jsonDeterministicOutboundIP : (string)_deterministicOutboundIP;} + {_publicNetworkAccess = If( json?.PropertyT("publicNetworkAccess"), out var __jsonPublicNetworkAccess) ? (string)__jsonPublicNetworkAccess : (string)_publicNetworkAccess;} + {_grafanaPlugin = If( json?.PropertyT("grafanaPlugins"), out var __jsonGrafanaPlugins) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.FromJson(__jsonGrafanaPlugins) : _grafanaPlugin;} + {_grafanaMajorVersion = If( json?.PropertyT("grafanaMajorVersion"), out var __jsonGrafanaMajorVersion) ? (string)__jsonGrafanaMajorVersion : (string)_grafanaMajorVersion;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._grafanaIntegration ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._grafanaIntegration.ToJson(null,serializationMode) : null, "grafanaIntegrations" ,container.Add ); + AddIf( null != this._enterpriseConfiguration ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._enterpriseConfiguration.ToJson(null,serializationMode) : null, "enterpriseConfigurations" ,container.Add ); + AddIf( null != this._grafanaConfiguration ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._grafanaConfiguration.ToJson(null,serializationMode) : null, "grafanaConfigurations" ,container.Add ); + AddIf( null != (((object)this._zoneRedundancy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._zoneRedundancy.ToString()) : null, "zoneRedundancy" ,container.Add ); + AddIf( null != (((object)this._apiKey)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._apiKey.ToString()) : null, "apiKey" ,container.Add ); + AddIf( null != (((object)this._deterministicOutboundIP)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._deterministicOutboundIP.ToString()) : null, "deterministicOutboundIP" ,container.Add ); + AddIf( null != (((object)this._publicNetworkAccess)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._publicNetworkAccess.ToString()) : null, "publicNetworkAccess" ,container.Add ); + AddIf( null != this._grafanaPlugin ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._grafanaPlugin.ToJson(null,serializationMode) : null, "grafanaPlugins" ,container.Add ); + AddIf( null != (((object)this._grafanaMajorVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._grafanaMajorVersion.ToString()) : null, "grafanaMajorVersion" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.PowerShell.cs new file mode 100644 index 00000000000..2db39e13711 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter))] + public partial class ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins(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 ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins(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.Dashboard.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(); + } + } + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter))] + public partial interface IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.TypeConverter.cs new file mode 100644 index 00000000000..7738918d890 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.cs new file mode 100644 index 00000000000..608882a9f02 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + public partial class ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPluginsInternal + { + + /// + /// Creates an new instance. + /// + public ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins() + { + + } + } + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + public partial interface IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + internal partial interface IManagedGrafanaPropertiesUpdateParametersGrafanaPluginsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.dictionary.cs new file mode 100644 index 00000000000..f3a5d6489a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaPlugin 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.Dashboard.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.Dashboard.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.Dashboard.Models.IGrafanaPlugin value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.json.cs new file mode 100644 index 00000000000..ab2e521566b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + public partial class ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedGrafanaPropertiesUpdateParametersGrafanaPlugins(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaPlugin.FromJson(j) ,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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.PowerShell.cs new file mode 100644 index 00000000000..55ec2821249 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaTagsTypeConverter))] + public partial class ManagedGrafanaTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaTags(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 ManagedGrafanaTags(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.Dashboard.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(ManagedGrafanaTagsTypeConverter))] + public partial interface IManagedGrafanaTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.TypeConverter.cs new file mode 100644 index 00000000000..116c98347ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.cs new file mode 100644 index 00000000000..cf745129073 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Resource tags. + public partial class ManagedGrafanaTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTagsInternal + { + + /// Creates an new instance. + public ManagedGrafanaTags() + { + + } + } + /// Resource tags. + public partial interface IManagedGrafanaTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface IManagedGrafanaTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.dictionary.cs new file mode 100644 index 00000000000..f434a658a9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedGrafanaTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.ManagedGrafanaTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.json.cs new file mode 100644 index 00000000000..3a943445766 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Resource tags. + public partial class ManagedGrafanaTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedGrafanaTags(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.PowerShell.cs new file mode 100644 index 00000000000..bd9306c8fba --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.PowerShell.cs @@ -0,0 +1,466 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The parameters for a PATCH request to a grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaUpdateParametersTypeConverter))] + public partial class ManagedGrafanaUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaUpdateParameters(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.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSkuTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaUpdateParametersTagsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SkuName, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedGrafanaUpdateParameters(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.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSkuTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaUpdateParametersTagsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations) content.GetValueForProperty("GrafanaIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaIntegrationsTypeConverter.ConvertFrom); + } + if (content.Contains("EnterpriseConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations) content.GetValueForProperty("EnterpriseConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.EnterpriseConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfiguration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations) content.GetValueForProperty("GrafanaConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfiguration, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.GrafanaConfigurationsTypeConverter.ConvertFrom); + } + if (content.Contains("ZoneRedundancy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ZoneRedundancy = (string) content.GetValueForProperty("ZoneRedundancy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ZoneRedundancy, global::System.Convert.ToString); + } + if (content.Contains("ApiKey")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ApiKey = (string) content.GetValueForProperty("ApiKey",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).ApiKey, global::System.Convert.ToString); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SkuName, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("DeterministicOutboundIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).DeterministicOutboundIP = (string) content.GetValueForProperty("DeterministicOutboundIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).DeterministicOutboundIP, global::System.Convert.ToString); + } + if (content.Contains("PublicNetworkAccess")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).PublicNetworkAccess = (string) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).PublicNetworkAccess, global::System.Convert.ToString); + } + if (content.Contains("GrafanaPlugin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins) content.GetValueForProperty("GrafanaPlugin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaPlugin, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParametersGrafanaPluginsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaMajorVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaMajorVersion = (string) content.GetValueForProperty("GrafanaMajorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaMajorVersion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationSmtp")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSmtp = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp) content.GetValueForProperty("GrafanaConfigurationSmtp",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSmtp, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SmtpTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSnapshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSnapshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots) content.GetValueForProperty("GrafanaConfigurationSnapshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSnapshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SnapshotsTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUser = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers) content.GetValueForProperty("GrafanaConfigurationUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUser, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UsersTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaConfigurationSecurity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSecurity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity) content.GetValueForProperty("GrafanaConfigurationSecurity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationSecurity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SecurityTypeConverter.ConvertFrom); + } + if (content.Contains("GrafanaIntegrationAzureMonitorWorkspaceIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration = (System.Collections.Generic.List) content.GetValueForProperty("GrafanaIntegrationAzureMonitorWorkspaceIntegration",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaIntegrationAzureMonitorWorkspaceIntegration, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.AzureMonitorWorkspaceIntegrationTypeConverter.ConvertFrom)); + } + if (content.Contains("EnterpriseConfigurationMarketplacePlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplacePlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplacePlanId, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseConfigurationMarketplaceAutoRenew")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew = (string) content.GetValueForProperty("EnterpriseConfigurationMarketplaceAutoRenew",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).EnterpriseConfigurationMarketplaceAutoRenew, global::System.Convert.ToString); + } + if (content.Contains("GrafanaConfigurationUnifiedAlertingScreenshot")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots) content.GetValueForProperty("GrafanaConfigurationUnifiedAlertingScreenshot",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).GrafanaConfigurationUnifiedAlertingScreenshot, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UnifiedAlertingScreenshotsTypeConverter.ConvertFrom); + } + if (content.Contains("SmtpEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpEnabled = (bool?) content.GetValueForProperty("SmtpEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SmtpHost")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpHost = (string) content.GetValueForProperty("SmtpHost",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpHost, global::System.Convert.ToString); + } + if (content.Contains("SmtpUser")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpUser = (string) content.GetValueForProperty("SmtpUser",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpUser, global::System.Convert.ToString); + } + if (content.Contains("SmtpPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpPassword = (System.Security.SecureString) content.GetValueForProperty("SmtpPassword",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpPassword, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("SmtpFromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromAddress = (string) content.GetValueForProperty("SmtpFromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromAddress, global::System.Convert.ToString); + } + if (content.Contains("SmtpFromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromName = (string) content.GetValueForProperty("SmtpFromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpFromName, global::System.Convert.ToString); + } + if (content.Contains("SmtpStartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpStartTlsPolicy = (string) content.GetValueForProperty("SmtpStartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpStartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SmtpSkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpSkipVerify = (bool?) content.GetValueForProperty("SmtpSkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SmtpSkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SnapshotExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SnapshotExternalEnabled = (bool?) content.GetValueForProperty("SnapshotExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SnapshotExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserViewersCanEdit = (bool?) content.GetValueForProperty("UserViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UserEditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserEditorsCanAdmin = (bool?) content.GetValueForProperty("UserEditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UserEditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SecurityCsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SecurityCsrfAlwaysCheck = (bool?) content.GetValueForProperty("SecurityCsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).SecurityCsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("UnifiedAlertingScreenshotCaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled = (bool?) content.GetValueForProperty("UnifiedAlertingScreenshotCaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal)this).UnifiedAlertingScreenshotCaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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 for a PATCH request to a grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaUpdateParametersTypeConverter))] + public partial interface IManagedGrafanaUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.TypeConverter.cs new file mode 100644 index 00000000000..d44b83f21f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.cs new file mode 100644 index 00000000000..eaec7b5d122 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.cs @@ -0,0 +1,707 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a grafana resource. + public partial class ManagedGrafanaUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal + { + + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ApiKey { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).ApiKey; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).ApiKey = value ?? null; } + + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DeterministicOutboundIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).DeterministicOutboundIP; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).DeterministicOutboundIP = value ?? null; } + + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).EnterpriseConfigurationMarketplaceAutoRenew; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).EnterpriseConfigurationMarketplaceAutoRenew = value ?? null; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string EnterpriseConfigurationMarketplacePlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).EnterpriseConfigurationMarketplacePlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).EnterpriseConfigurationMarketplacePlanId = value ?? null; } + + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaIntegrationAzureMonitorWorkspaceIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaIntegrationAzureMonitorWorkspaceIntegration = value ?? null /* arrayOf */; } + + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string GrafanaMajorVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaMajorVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaMajorVersion = value ?? null; } + + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins GrafanaPlugin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaPlugin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaPlugin = value ?? null /* model class */; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity _identity; + + /// The managed identity of the grafana resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// Internal Acessors for EnterpriseConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.EnterpriseConfiguration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).EnterpriseConfiguration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).EnterpriseConfiguration = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfiguration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaConfiguration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfiguration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfiguration = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSecurity + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaConfigurationSecurity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationSecurity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationSecurity = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSmtp + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaConfigurationSmtp { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationSmtp; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationSmtp = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationSnapshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaConfigurationSnapshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationSnapshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationSnapshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUnifiedAlertingScreenshot + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaConfigurationUnifiedAlertingScreenshot { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationUnifiedAlertingScreenshot; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationUnifiedAlertingScreenshot = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaConfigurationUser + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaConfigurationUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationUser; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaConfigurationUser = value ?? null /* model class */; } + + /// Internal Acessors for GrafanaIntegration + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.GrafanaIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).GrafanaIntegration = value ?? null /* model class */; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParameters()); set { {_property = value;} } } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSku()); set { {_sku = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters _property; + + /// Properties specific to the managed grafana resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParameters()); set => this._property = value; } + + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PublicNetworkAccess { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).PublicNetworkAccess; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).PublicNetworkAccess = value ?? null; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SecurityCsrfAlwaysCheck { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SecurityCsrfAlwaysCheck; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SecurityCsrfAlwaysCheck = value ?? default(bool); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku _sku; + + /// Represents the SKU of a resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ResourceSku()); set => this._sku = value; } + + /// The name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal)Sku).Name = value ?? null; } + + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpEnabled = value ?? default(bool); } + + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpFromAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpFromAddress = value ?? null; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpFromName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpFromName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpFromName = value ?? null; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpHost { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpHost; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpHost = value ?? null; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Security.SecureString SmtpPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpPassword; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpPassword = value ?? null; } + + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SmtpSkipVerify { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpSkipVerify; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpSkipVerify = value ?? default(bool); } + + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpStartTlsPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpStartTlsPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpStartTlsPolicy = value ?? null; } + + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SmtpUser { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpUser; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SmtpUser = value ?? null; } + + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? SnapshotExternalEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SnapshotExternalEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).SnapshotExternalEnabled = value ?? default(bool); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags _tag; + + /// The new tags of the grafana resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaUpdateParametersTags()); set => this._tag = value; } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UnifiedAlertingScreenshotCaptureEnabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).UnifiedAlertingScreenshotCaptureEnabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).UnifiedAlertingScreenshotCaptureEnabled = value ?? default(bool); } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserEditorsCanAdmin { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).UserEditorsCanAdmin; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).UserEditorsCanAdmin = value ?? default(bool); } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public bool? UserViewersCanEdit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).UserViewersCanEdit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).UserViewersCanEdit = value ?? default(bool); } + + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ZoneRedundancy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).ZoneRedundancy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersInternal)Property).ZoneRedundancy = value ?? null; } + + /// Creates an new instance. + public ManagedGrafanaUpdateParameters() + { + + } + } + /// The parameters for a PATCH request to a grafana resource. + public partial interface IManagedGrafanaUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The api key setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// The AutoRenew setting of the Enterprise subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + string GrafanaMajorVersion { get; set; } + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given plugin id will be removed. Otherwise, given plugin will be installed.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins GrafanaPlugin { 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Indicate the state for enable or disable traffic over the public interface. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(bool) })] + bool? SecurityCsrfAlwaysCheck { get; set; } + /// The name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string SkuName { get; set; } + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Address used when sending out emails + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification"" + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Verify SSL for SMTP server. Default is false + https://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(bool) })] + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The StartTLSPolicy setting of the SMTP configuration + https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? SnapshotExternalEnabled { get; set; } + /// The new tags of the grafana resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The new tags of the grafana resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags Tag { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(bool) })] + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(bool) })] + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } + /// The parameters for a PATCH request to a grafana resource. + internal partial interface IManagedGrafanaUpdateParametersInternal + + { + /// The api key setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ApiKey { get; set; } + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string DeterministicOutboundIP { get; set; } + /// Enterprise settings of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseConfigurations EnterpriseConfiguration { get; set; } + /// The AutoRenew setting of the Enterprise subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string EnterpriseConfigurationMarketplaceAutoRenew { get; set; } + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + string EnterpriseConfigurationMarketplacePlanId { get; set; } + /// Server configurations of a Grafana instance + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaConfigurations GrafanaConfiguration { get; set; } + /// Grafana security settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity GrafanaConfigurationSecurity { get; set; } + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp GrafanaConfigurationSmtp { get; set; } + /// Grafana Snapshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots GrafanaConfigurationSnapshot { get; set; } + /// Grafana Unified Alerting Screenshots settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots GrafanaConfigurationUnifiedAlertingScreenshot { get; set; } + /// Grafana users settings + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers GrafanaConfigurationUser { get; set; } + /// + /// GrafanaIntegrations is a bundled observability experience (e.g. pre-configured data source, tailored Grafana dashboards, + /// alerting defaults) for common monitoring scenarios. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaIntegrations GrafanaIntegration { get; set; } + /// Array of AzureMonitorWorkspaceIntegration + System.Collections.Generic.List GrafanaIntegrationAzureMonitorWorkspaceIntegration { get; set; } + /// The major Grafana software version to target. + string GrafanaMajorVersion { get; set; } + /// + /// Update of Grafana plugin. Key is plugin id, value is plugin definition. If plugin definition is null, plugin with given + /// plugin id will be removed. Otherwise, given plugin will be installed. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParametersGrafanaPlugins GrafanaPlugin { get; set; } + /// The managed identity of the grafana resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Properties specific to the managed grafana resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesUpdateParameters Property { get; set; } + /// Indicate the state for enable or disable traffic over the public interface. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + string PublicNetworkAccess { get; set; } + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + bool? SecurityCsrfAlwaysCheck { get; set; } + /// Represents the SKU of a resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku Sku { get; set; } + /// The name of the SKU. + string SkuName { get; set; } + /// Enable this to allow Grafana to send email. Default is false + bool? SmtpEnabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + string SmtpFromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + string SmtpHost { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + System.Security.SecureString SmtpPassword { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + bool? SmtpSkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string SmtpStartTlsPolicy { get; set; } + /// User of SMTP auth + string SmtpUser { get; set; } + /// Set to false to disable external snapshot publish endpoint + bool? SnapshotExternalEnabled { get; set; } + /// The new tags of the grafana resource. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags Tag { get; set; } + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + bool? UnifiedAlertingScreenshotCaptureEnabled { get; set; } + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + bool? UserEditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + bool? UserViewersCanEdit { get; set; } + /// The zone redundancy setting of the Grafana instance. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + string ZoneRedundancy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.json.cs new file mode 100644 index 00000000000..03e0e87896c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a grafana resource. + public partial class ManagedGrafanaUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaUpdateParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedGrafanaUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ResourceSku.FromJson(__jsonSku) : _sku;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaPropertiesUpdateParameters.FromJson(__jsonProperties) : _property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafanaUpdateParametersTags.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.PowerShell.cs new file mode 100644 index 00000000000..7c463baf60d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.PowerShell.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The new tags of the grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaUpdateParametersTagsTypeConverter))] + public partial class ManagedGrafanaUpdateParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedGrafanaUpdateParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedGrafanaUpdateParametersTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedGrafanaUpdateParametersTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedGrafanaUpdateParametersTags(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 ManagedGrafanaUpdateParametersTags(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.Dashboard.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 new tags of the grafana resource. + [System.ComponentModel.TypeConverter(typeof(ManagedGrafanaUpdateParametersTagsTypeConverter))] + public partial interface IManagedGrafanaUpdateParametersTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.TypeConverter.cs new file mode 100644 index 00000000000..b33c194158e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedGrafanaUpdateParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedGrafanaUpdateParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedGrafanaUpdateParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedGrafanaUpdateParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedGrafanaUpdateParametersTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.cs new file mode 100644 index 00000000000..b227fb5001a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the grafana resource. + public partial class ManagedGrafanaUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTagsInternal + { + + /// Creates an new instance. + public ManagedGrafanaUpdateParametersTags() + { + + } + } + /// The new tags of the grafana resource. + public partial interface IManagedGrafanaUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// The new tags of the grafana resource. + internal partial interface IManagedGrafanaUpdateParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.dictionary.cs new file mode 100644 index 00000000000..70f2d0aac21 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedGrafanaUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.ManagedGrafanaUpdateParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.json.cs new file mode 100644 index 00000000000..d8e6aadd8e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedGrafanaUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the grafana resource. + public partial class ManagedGrafanaUpdateParametersTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedGrafanaUpdateParametersTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedGrafanaUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.PowerShell.cs new file mode 100644 index 00000000000..8de53f11fa4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The state of managed private endpoint connection. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointConnectionStateTypeConverter))] + public partial class ManagedPrivateEndpointConnectionState + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedPrivateEndpointConnectionState DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedPrivateEndpointConnectionState(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedPrivateEndpointConnectionState(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedPrivateEndpointConnectionState(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)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 ManagedPrivateEndpointConnectionState(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)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.Dashboard.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 state of managed private endpoint connection. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointConnectionStateTypeConverter))] + public partial interface IManagedPrivateEndpointConnectionState + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.TypeConverter.cs new file mode 100644 index 00000000000..27a07dd99bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedPrivateEndpointConnectionStateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedPrivateEndpointConnectionState ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedPrivateEndpointConnectionState.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointConnectionState.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointConnectionState.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.cs new file mode 100644 index 00000000000..f4c8c935bf2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The state of managed private endpoint connection. + public partial class ManagedPrivateEndpointConnectionState : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal + { + + /// Backing field for property. + private string _description; + + /// Gets or sets the reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal.Status { get => this._status; set { {_status = value;} } } + + /// Backing field for property. + private string _status; + + /// The approval/rejection status of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Creates an new instance. + public ManagedPrivateEndpointConnectionState() + { + + } + } + /// The state of managed private endpoint connection. + public partial interface IManagedPrivateEndpointConnectionState : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Gets or sets the reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the reason for approval/rejection of the connection.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// The approval/rejection status of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The approval/rejection status of managed private endpoint connection.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected", "Disconnected")] + string Status { get; } + + } + /// The state of managed private endpoint connection. + internal partial interface IManagedPrivateEndpointConnectionStateInternal + + { + /// Gets or sets the reason for approval/rejection of the connection. + string Description { get; set; } + /// The approval/rejection status of managed private endpoint connection. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected", "Disconnected")] + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.json.cs new file mode 100644 index 00000000000..199256a1b4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointConnectionState.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The state of managed private endpoint connection. + public partial class ManagedPrivateEndpointConnectionState + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedPrivateEndpointConnectionState(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedPrivateEndpointConnectionState(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.PowerShell.cs new file mode 100644 index 00000000000..be630d75413 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.PowerShell.cs @@ -0,0 +1,338 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The managed private endpoint resource type. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointModelTypeConverter))] + public partial class ManagedPrivateEndpointModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedPrivateEndpointModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedPrivateEndpointModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedPrivateEndpointModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedPrivateEndpointModel(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.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState) content.GetValueForProperty("ConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceId = (string) content.GetValueForProperty("PrivateLinkResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceRegion = (string) content.GetValueForProperty("PrivateLinkResourceRegion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceRegion, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequestMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).RequestMessage = (string) content.GetValueForProperty("RequestMessage",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).RequestMessage, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServiceUrl = (string) content.GetValueForProperty("PrivateLinkServiceUrl",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServiceUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServicePrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServicePrivateIP = (string) content.GetValueForProperty("PrivateLinkServicePrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServicePrivateIP, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateStatus = (string) content.GetValueForProperty("ConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateDescription = (string) content.GetValueForProperty("ConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateDescription, 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 ManagedPrivateEndpointModel(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.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState) content.GetValueForProperty("ConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceId = (string) content.GetValueForProperty("PrivateLinkResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceRegion = (string) content.GetValueForProperty("PrivateLinkResourceRegion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkResourceRegion, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequestMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).RequestMessage = (string) content.GetValueForProperty("RequestMessage",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).RequestMessage, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServiceUrl = (string) content.GetValueForProperty("PrivateLinkServiceUrl",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServiceUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServicePrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServicePrivateIP = (string) content.GetValueForProperty("PrivateLinkServicePrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).PrivateLinkServicePrivateIP, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateStatus = (string) content.GetValueForProperty("ConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateDescription = (string) content.GetValueForProperty("ConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal)this).ConnectionStateDescription, 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.Dashboard.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 managed private endpoint resource type. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointModelTypeConverter))] + public partial interface IManagedPrivateEndpointModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.TypeConverter.cs new file mode 100644 index 00000000000..ce8efcba0fc --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedPrivateEndpointModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedPrivateEndpointModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedPrivateEndpointModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.cs new file mode 100644 index 00000000000..4af5c47fddf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.cs @@ -0,0 +1,351 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The managed private endpoint resource type. + public partial class ManagedPrivateEndpointModel : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResource(); + + /// Gets or sets the reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionStateDescription; } + + /// The approval/rejection status of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionStateStatus; } + + /// The group Ids of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List GroupId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).GroupId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).GroupId = value ?? null /* arrayOf */; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for ConnectionState + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal.ConnectionState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionState = value ?? null /* model class */; } + + /// Internal Acessors for ConnectionStateDescription + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal.ConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionStateDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionStateDescription = value ?? null; } + + /// Internal Acessors for ConnectionStateStatus + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal.ConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionStateStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ConnectionStateStatus = value ?? null; } + + /// Internal Acessors for PrivateLinkServicePrivateIP + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal.PrivateLinkServicePrivateIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkServicePrivateIP; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkServicePrivateIP = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Name; } + + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkResourceId = value ?? null; } + + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkResourceRegion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkResourceRegion; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkResourceRegion = value ?? null; } + + /// + /// The private IP of private endpoint after approval. This property is empty before connection is approved. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServicePrivateIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkServicePrivateIP; } + + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkServiceUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).PrivateLinkServiceUrl = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties _property; + + /// Resource properties. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).ProvisioningState; } + + /// User input request message of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string RequestMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).RequestMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)Property).RequestMessage = value ?? null; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public ManagedPrivateEndpointModel() + { + + } + + /// 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.Dashboard.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// The managed private endpoint resource type. + public partial interface IManagedPrivateEndpointModel : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource + { + /// Gets or sets the reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the reason for approval/rejection of the connection.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string ConnectionStateDescription { get; } + /// The approval/rejection status of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The approval/rejection status of managed private endpoint connection.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected", "Disconnected")] + string ConnectionStateStatus { get; } + /// The group Ids of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The group Ids of the managed private endpoint.", + SerializedName = @"groupIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List GroupId { get; set; } + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ARM resource ID of the resource for which the managed private endpoint is pointing to.", + SerializedName = @"privateLinkResourceId", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkResourceId { get; set; } + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The region of the resource to which the managed private endpoint is pointing to.", + SerializedName = @"privateLinkResourceRegion", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkResourceRegion { get; set; } + /// + /// The private IP of private endpoint after approval. This property is empty before connection is approved. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private IP of private endpoint after approval. This property is empty before connection is approved.", + SerializedName = @"privateLinkServicePrivateIP", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServicePrivateIP { get; } + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration page without the protocol and port.", + SerializedName = @"privateLinkServiceUrl", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceUrl { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// User input request message of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"User input request message of the managed private endpoint.", + SerializedName = @"requestMessage", + PossibleTypes = new [] { typeof(string) })] + string RequestMessage { get; set; } + + } + /// The managed private endpoint resource type. + internal partial interface IManagedPrivateEndpointModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal + { + /// The state of managed private endpoint connection. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState ConnectionState { get; set; } + /// Gets or sets the reason for approval/rejection of the connection. + string ConnectionStateDescription { get; set; } + /// The approval/rejection status of managed private endpoint connection. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected", "Disconnected")] + string ConnectionStateStatus { get; set; } + /// The group Ids of the managed private endpoint. + System.Collections.Generic.List GroupId { get; set; } + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + string PrivateLinkResourceId { get; set; } + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + string PrivateLinkResourceRegion { get; set; } + /// + /// The private IP of private endpoint after approval. This property is empty before connection is approved. + /// + string PrivateLinkServicePrivateIP { get; set; } + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + string PrivateLinkServiceUrl { get; set; } + /// Resource properties. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// User input request message of the managed private endpoint. + string RequestMessage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.json.cs new file mode 100644 index 00000000000..80b0bedf4f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModel.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The managed private endpoint resource type. + public partial class ManagedPrivateEndpointModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedPrivateEndpointModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedPrivateEndpointModel(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelProperties.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.PowerShell.cs new file mode 100644 index 00000000000..4c77036f6fa --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The list of managed private endpoints of a grafana resource + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointModelListResponseTypeConverter))] + public partial class ManagedPrivateEndpointModelListResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedPrivateEndpointModelListResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedPrivateEndpointModelListResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedPrivateEndpointModelListResponse(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedPrivateEndpointModelListResponse(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.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)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 ManagedPrivateEndpointModelListResponse(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.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal)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.Dashboard.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 list of managed private endpoints of a grafana resource + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointModelListResponseTypeConverter))] + public partial interface IManagedPrivateEndpointModelListResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.TypeConverter.cs new file mode 100644 index 00000000000..b576038798c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedPrivateEndpointModelListResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedPrivateEndpointModelListResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedPrivateEndpointModelListResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointModelListResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointModelListResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.cs new file mode 100644 index 00000000000..998a0e1391a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The list of managed private endpoints of a grafana resource + public partial class ManagedPrivateEndpointModelListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponseInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The ManagedPrivateEndpointModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ManagedPrivateEndpointModelListResponse() + { + + } + } + /// The list of managed private endpoints of a grafana resource + public partial interface IManagedPrivateEndpointModelListResponse : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 ManagedPrivateEndpointModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ManagedPrivateEndpointModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The list of managed private endpoints of a grafana resource + internal partial interface IManagedPrivateEndpointModelListResponseInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The ManagedPrivateEndpointModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.json.cs new file mode 100644 index 00000000000..b67b5de629a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelListResponse.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The list of managed private endpoints of a grafana resource + public partial class ManagedPrivateEndpointModelListResponse + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelListResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedPrivateEndpointModelListResponse(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedPrivateEndpointModelListResponse(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.PowerShell.cs new file mode 100644 index 00000000000..632ae3a1a2a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.PowerShell.cs @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Properties specific to the managed private endpoint. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointModelPropertiesTypeConverter))] + public partial class ManagedPrivateEndpointModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedPrivateEndpointModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedPrivateEndpointModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedPrivateEndpointModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedPrivateEndpointModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState) content.GetValueForProperty("ConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceId = (string) content.GetValueForProperty("PrivateLinkResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceRegion = (string) content.GetValueForProperty("PrivateLinkResourceRegion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceRegion, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequestMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).RequestMessage = (string) content.GetValueForProperty("RequestMessage",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).RequestMessage, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServiceUrl = (string) content.GetValueForProperty("PrivateLinkServiceUrl",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServiceUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServicePrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServicePrivateIP = (string) content.GetValueForProperty("PrivateLinkServicePrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServicePrivateIP, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateStatus = (string) content.GetValueForProperty("ConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateDescription = (string) content.GetValueForProperty("ConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateDescription, 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 ManagedPrivateEndpointModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState) content.GetValueForProperty("ConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceId = (string) content.GetValueForProperty("PrivateLinkResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceRegion = (string) content.GetValueForProperty("PrivateLinkResourceRegion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkResourceRegion, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequestMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).RequestMessage = (string) content.GetValueForProperty("RequestMessage",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).RequestMessage, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServiceUrl = (string) content.GetValueForProperty("PrivateLinkServiceUrl",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServiceUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServicePrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServicePrivateIP = (string) content.GetValueForProperty("PrivateLinkServicePrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).PrivateLinkServicePrivateIP, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateStatus = (string) content.GetValueForProperty("ConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("ConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateDescription = (string) content.GetValueForProperty("ConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal)this).ConnectionStateDescription, 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.Dashboard.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 managed private endpoint. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointModelPropertiesTypeConverter))] + public partial interface IManagedPrivateEndpointModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..d1d16883b21 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedPrivateEndpointModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedPrivateEndpointModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedPrivateEndpointModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.cs new file mode 100644 index 00000000000..15b7798a732 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties specific to the managed private endpoint. + public partial class ManagedPrivateEndpointModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState _connectionState; + + /// The state of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState ConnectionState { get => (this._connectionState = this._connectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionState()); } + + /// Gets or sets the reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)ConnectionState).Description; } + + /// The approval/rejection status of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)ConnectionState).Status; } + + /// Backing field for property. + private System.Collections.Generic.List _groupId; + + /// The group Ids of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List GroupId { get => this._groupId; set => this._groupId = value; } + + /// Internal Acessors for ConnectionState + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal.ConnectionState { get => (this._connectionState = this._connectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionState()); set { {_connectionState = value;} } } + + /// Internal Acessors for ConnectionStateDescription + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal.ConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)ConnectionState).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)ConnectionState).Description = value ?? null; } + + /// Internal Acessors for ConnectionStateStatus + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal.ConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)ConnectionState).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionStateInternal)ConnectionState).Status = value ?? null; } + + /// Internal Acessors for PrivateLinkServicePrivateIP + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal.PrivateLinkServicePrivateIP { get => this._privateLinkServicePrivateIP; set { {_privateLinkServicePrivateIP = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _privateLinkResourceId; + + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PrivateLinkResourceId { get => this._privateLinkResourceId; set => this._privateLinkResourceId = value; } + + /// Backing field for property. + private string _privateLinkResourceRegion; + + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PrivateLinkResourceRegion { get => this._privateLinkResourceRegion; set => this._privateLinkResourceRegion = value; } + + /// Backing field for property. + private string _privateLinkServicePrivateIP; + + /// + /// The private IP of private endpoint after approval. This property is empty before connection is approved. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PrivateLinkServicePrivateIP { get => this._privateLinkServicePrivateIP; } + + /// Backing field for property. + private string _privateLinkServiceUrl; + + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PrivateLinkServiceUrl { get => this._privateLinkServiceUrl; set => this._privateLinkServiceUrl = value; } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _requestMessage; + + /// User input request message of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string RequestMessage { get => this._requestMessage; set => this._requestMessage = value; } + + /// Creates an new instance. + public ManagedPrivateEndpointModelProperties() + { + + } + } + /// Properties specific to the managed private endpoint. + public partial interface IManagedPrivateEndpointModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Gets or sets the reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the reason for approval/rejection of the connection.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string ConnectionStateDescription { get; } + /// The approval/rejection status of managed private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The approval/rejection status of managed private endpoint connection.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected", "Disconnected")] + string ConnectionStateStatus { get; } + /// The group Ids of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The group Ids of the managed private endpoint.", + SerializedName = @"groupIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List GroupId { get; set; } + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ARM resource ID of the resource for which the managed private endpoint is pointing to.", + SerializedName = @"privateLinkResourceId", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkResourceId { get; set; } + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The region of the resource to which the managed private endpoint is pointing to.", + SerializedName = @"privateLinkResourceRegion", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkResourceRegion { get; set; } + /// + /// The private IP of private endpoint after approval. This property is empty before connection is approved. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private IP of private endpoint after approval. This property is empty before connection is approved.", + SerializedName = @"privateLinkServicePrivateIP", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServicePrivateIP { get; } + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration page without the protocol and port.", + SerializedName = @"privateLinkServiceUrl", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceUrl { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// User input request message of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"User input request message of the managed private endpoint.", + SerializedName = @"requestMessage", + PossibleTypes = new [] { typeof(string) })] + string RequestMessage { get; set; } + + } + /// Properties specific to the managed private endpoint. + internal partial interface IManagedPrivateEndpointModelPropertiesInternal + + { + /// The state of managed private endpoint connection. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointConnectionState ConnectionState { get; set; } + /// Gets or sets the reason for approval/rejection of the connection. + string ConnectionStateDescription { get; set; } + /// The approval/rejection status of managed private endpoint connection. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected", "Disconnected")] + string ConnectionStateStatus { get; set; } + /// The group Ids of the managed private endpoint. + System.Collections.Generic.List GroupId { get; set; } + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + string PrivateLinkResourceId { get; set; } + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + string PrivateLinkResourceRegion { get; set; } + /// + /// The private IP of private endpoint after approval. This property is empty before connection is approved. + /// + string PrivateLinkServicePrivateIP { get; set; } + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + string PrivateLinkServiceUrl { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// User input request message of the managed private endpoint. + string RequestMessage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.json.cs new file mode 100644 index 00000000000..d45e5720542 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointModelProperties.json.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties specific to the managed private endpoint. + public partial class ManagedPrivateEndpointModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedPrivateEndpointModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedPrivateEndpointModelProperties(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_connectionState = If( json?.PropertyT("connectionState"), out var __jsonConnectionState) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointConnectionState.FromJson(__jsonConnectionState) : _connectionState;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_privateLinkResourceId = If( json?.PropertyT("privateLinkResourceId"), out var __jsonPrivateLinkResourceId) ? (string)__jsonPrivateLinkResourceId : (string)_privateLinkResourceId;} + {_privateLinkResourceRegion = If( json?.PropertyT("privateLinkResourceRegion"), out var __jsonPrivateLinkResourceRegion) ? (string)__jsonPrivateLinkResourceRegion : (string)_privateLinkResourceRegion;} + {_groupId = If( json?.PropertyT("groupIds"), out var __jsonGroupIds) ? If( __jsonGroupIds as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _groupId;} + {_requestMessage = If( json?.PropertyT("requestMessage"), out var __jsonRequestMessage) ? (string)__jsonRequestMessage : (string)_requestMessage;} + {_privateLinkServiceUrl = If( json?.PropertyT("privateLinkServiceUrl"), out var __jsonPrivateLinkServiceUrl) ? (string)__jsonPrivateLinkServiceUrl : (string)_privateLinkServiceUrl;} + {_privateLinkServicePrivateIP = If( json?.PropertyT("privateLinkServicePrivateIP"), out var __jsonPrivateLinkServicePrivateIP) ? (string)__jsonPrivateLinkServicePrivateIP : (string)_privateLinkServicePrivateIP;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._connectionState ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._connectionState.ToJson(null,serializationMode) : null, "connectionState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._privateLinkResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._privateLinkResourceId.ToString()) : null, "privateLinkResourceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._privateLinkResourceRegion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._privateLinkResourceRegion.ToString()) : null, "privateLinkResourceRegion" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + if (null != this._groupId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._groupId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("groupIds",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._requestMessage)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._requestMessage.ToString()) : null, "requestMessage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._privateLinkServiceUrl)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._privateLinkServiceUrl.ToString()) : null, "privateLinkServiceUrl" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._privateLinkServicePrivateIP)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._privateLinkServicePrivateIP.ToString()) : null, "privateLinkServicePrivateIP" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.PowerShell.cs new file mode 100644 index 00000000000..1c1bf1867e3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The parameters for a PATCH request to a managed private endpoint. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointUpdateParametersTypeConverter))] + public partial class ManagedPrivateEndpointUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedPrivateEndpointUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedPrivateEndpointUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedPrivateEndpointUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedPrivateEndpointUpdateParameters(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.Dashboard.Models.IManagedPrivateEndpointUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParametersTagsTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedPrivateEndpointUpdateParameters(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.Dashboard.Models.IManagedPrivateEndpointUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParametersTagsTypeConverter.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.Dashboard.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 for a PATCH request to a managed private endpoint. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointUpdateParametersTypeConverter))] + public partial interface IManagedPrivateEndpointUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.TypeConverter.cs new file mode 100644 index 00000000000..91054aaf59c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedPrivateEndpointUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedPrivateEndpointUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedPrivateEndpointUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.cs new file mode 100644 index 00000000000..71a5aa55385 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a managed private endpoint. + public partial class ManagedPrivateEndpointUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags _tag; + + /// The new tags of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParametersTags()); set => this._tag = value; } + + /// Creates an new instance. + public ManagedPrivateEndpointUpdateParameters() + { + + } + } + /// The parameters for a PATCH request to a managed private endpoint. + public partial interface IManagedPrivateEndpointUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The new tags of the managed private endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The new tags of the managed private endpoint.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags Tag { get; set; } + + } + /// The parameters for a PATCH request to a managed private endpoint. + internal partial interface IManagedPrivateEndpointUpdateParametersInternal + + { + /// The new tags of the managed private endpoint. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.json.cs new file mode 100644 index 00000000000..c3aa2924554 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParameters.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The parameters for a PATCH request to a managed private endpoint. + public partial class ManagedPrivateEndpointUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedPrivateEndpointUpdateParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedPrivateEndpointUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParametersTags.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.PowerShell.cs new file mode 100644 index 00000000000..9b24ed271a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.PowerShell.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The new tags of the managed private endpoint. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointUpdateParametersTagsTypeConverter))] + public partial class ManagedPrivateEndpointUpdateParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedPrivateEndpointUpdateParametersTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedPrivateEndpointUpdateParametersTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a + /// json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedPrivateEndpointUpdateParametersTags(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 ManagedPrivateEndpointUpdateParametersTags(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.Dashboard.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 new tags of the managed private endpoint. + [System.ComponentModel.TypeConverter(typeof(ManagedPrivateEndpointUpdateParametersTagsTypeConverter))] + public partial interface IManagedPrivateEndpointUpdateParametersTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.TypeConverter.cs new file mode 100644 index 00000000000..974c7bc3965 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedPrivateEndpointUpdateParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedPrivateEndpointUpdateParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointUpdateParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedPrivateEndpointUpdateParametersTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.cs new file mode 100644 index 00000000000..87bcc9a6857 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the managed private endpoint. + public partial class ManagedPrivateEndpointUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTagsInternal + { + + /// + /// Creates an new instance. + /// + public ManagedPrivateEndpointUpdateParametersTags() + { + + } + } + /// The new tags of the managed private endpoint. + public partial interface IManagedPrivateEndpointUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// The new tags of the managed private endpoint. + internal partial interface IManagedPrivateEndpointUpdateParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.dictionary.cs new file mode 100644 index 00000000000..cdfd704d776 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedPrivateEndpointUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.ManagedPrivateEndpointUpdateParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.json.cs new file mode 100644 index 00000000000..bbaf7380732 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedPrivateEndpointUpdateParametersTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The new tags of the managed private endpoint. + public partial class ManagedPrivateEndpointUpdateParametersTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedPrivateEndpointUpdateParametersTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedPrivateEndpointUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs new file mode 100644 index 00000000000..4bec3fd5a3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedServiceIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.Dashboard.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs new file mode 100644 index 00000000000..7be9803edc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedServiceIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs new file mode 100644 index 00000000000..c6f5d847d2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities _userAssignedIdentity; + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get => (this._userAssignedIdentity = this._userAssignedIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentities()); 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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities 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.Dashboard.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs new file mode 100644 index 00000000000..f8659932c1a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedServiceIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedServiceIdentity(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentities.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != this._userAssignedIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs new file mode 100644 index 00000000000..d88833b03c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedServiceIdentityUserAssignedIdentities(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 ManagedServiceIdentityUserAssignedIdentities(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.Dashboard.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 identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial interface IManagedServiceIdentityUserAssignedIdentities + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs new file mode 100644 index 00000000000..0692272de21 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedServiceIdentityUserAssignedIdentitiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedServiceIdentityUserAssignedIdentities.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs new file mode 100644 index 00000000000..c64211fad38 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentitiesInternal + { + + /// + /// Creates an new instance. + /// + public ManagedServiceIdentityUserAssignedIdentities() + { + + } + } + /// The identities assigned to this resource by the user. + public partial interface IManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// The identities assigned to this resource by the user. + internal partial interface IManagedServiceIdentityUserAssignedIdentitiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs new file mode 100644 index 00000000000..eed406f29b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IUserAssignedIdentity value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedServiceIdentityUserAssignedIdentities source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs new file mode 100644 index 00000000000..7cfa1d3f51f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedServiceIdentityUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ManagedServiceIdentityUserAssignedIdentities(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedServiceIdentityUserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UserAssignedIdentity.FromJson(j) ,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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.PowerShell.cs new file mode 100644 index 00000000000..739acafd271 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// The allocation details of the per subscription free trial slot of the subscription. + /// + [System.ComponentModel.TypeConverter(typeof(MarketplaceTrialQuotaTypeConverter))] + public partial class MarketplaceTrialQuota + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IMarketplaceTrialQuota DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MarketplaceTrialQuota(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MarketplaceTrialQuota(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MarketplaceTrialQuota(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AvailablePromotion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).AvailablePromotion = (string) content.GetValueForProperty("AvailablePromotion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).AvailablePromotion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).GrafanaResourceId = (string) content.GetValueForProperty("GrafanaResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).GrafanaResourceId, global::System.Convert.ToString); + } + if (content.Contains("TrialStartAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialStartAt = (global::System.DateTime?) content.GetValueForProperty("TrialStartAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialStartAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TrialEndAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialEndAt = (global::System.DateTime?) content.GetValueForProperty("TrialEndAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialEndAt, (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 MarketplaceTrialQuota(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AvailablePromotion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).AvailablePromotion = (string) content.GetValueForProperty("AvailablePromotion",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).AvailablePromotion, global::System.Convert.ToString); + } + if (content.Contains("GrafanaResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).GrafanaResourceId = (string) content.GetValueForProperty("GrafanaResourceId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).GrafanaResourceId, global::System.Convert.ToString); + } + if (content.Contains("TrialStartAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialStartAt = (global::System.DateTime?) content.GetValueForProperty("TrialStartAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialStartAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TrialEndAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialEndAt = (global::System.DateTime?) content.GetValueForProperty("TrialEndAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal)this).TrialEndAt, (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.Dashboard.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 allocation details of the per subscription free trial slot of the subscription. + [System.ComponentModel.TypeConverter(typeof(MarketplaceTrialQuotaTypeConverter))] + public partial interface IMarketplaceTrialQuota + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.TypeConverter.cs new file mode 100644 index 00000000000..cd34a36ac2f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MarketplaceTrialQuotaTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IMarketplaceTrialQuota ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MarketplaceTrialQuota.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MarketplaceTrialQuota.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MarketplaceTrialQuota.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.cs new file mode 100644 index 00000000000..820be39249b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// The allocation details of the per subscription free trial slot of the subscription. + /// + public partial class MarketplaceTrialQuota : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuotaInternal + { + + /// Backing field for property. + private string _availablePromotion; + + /// Available enterprise promotion for the subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string AvailablePromotion { get => this._availablePromotion; set => this._availablePromotion = value; } + + /// Backing field for property. + private string _grafanaResourceId; + + /// Resource Id of the Grafana resource which is doing the trial. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string GrafanaResourceId { get => this._grafanaResourceId; set => this._grafanaResourceId = value; } + + /// Backing field for property. + private global::System.DateTime? _trialEndAt; + + /// The date and time in UTC of when the trial ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public global::System.DateTime? TrialEndAt { get => this._trialEndAt; set => this._trialEndAt = value; } + + /// Backing field for property. + private global::System.DateTime? _trialStartAt; + + /// The date and time in UTC of when the trial starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public global::System.DateTime? TrialStartAt { get => this._trialStartAt; set => this._trialStartAt = value; } + + /// Creates an new instance. + public MarketplaceTrialQuota() + { + + } + } + /// The allocation details of the per subscription free trial slot of the subscription. + public partial interface IMarketplaceTrialQuota : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Available enterprise promotion for the subscription + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Available enterprise promotion for the subscription", + SerializedName = @"availablePromotion", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("None", "FreeTrial")] + string AvailablePromotion { get; set; } + /// Resource Id of the Grafana resource which is doing the trial. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource Id of the Grafana resource which is doing the trial.", + SerializedName = @"grafanaResourceId", + PossibleTypes = new [] { typeof(string) })] + string GrafanaResourceId { get; set; } + /// The date and time in UTC of when the trial ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the trial ends.", + SerializedName = @"trialEndAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TrialEndAt { get; set; } + /// The date and time in UTC of when the trial starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the trial starts.", + SerializedName = @"trialStartAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TrialStartAt { get; set; } + + } + /// The allocation details of the per subscription free trial slot of the subscription. + internal partial interface IMarketplaceTrialQuotaInternal + + { + /// Available enterprise promotion for the subscription + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("None", "FreeTrial")] + string AvailablePromotion { get; set; } + /// Resource Id of the Grafana resource which is doing the trial. + string GrafanaResourceId { get; set; } + /// The date and time in UTC of when the trial ends. + global::System.DateTime? TrialEndAt { get; set; } + /// The date and time in UTC of when the trial starts. + global::System.DateTime? TrialStartAt { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.json.cs new file mode 100644 index 00000000000..9be5793544e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/MarketplaceTrialQuota.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// The allocation details of the per subscription free trial slot of the subscription. + /// + public partial class MarketplaceTrialQuota + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IMarketplaceTrialQuota FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new MarketplaceTrialQuota(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal MarketplaceTrialQuota(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_availablePromotion = If( json?.PropertyT("availablePromotion"), out var __jsonAvailablePromotion) ? (string)__jsonAvailablePromotion : (string)_availablePromotion;} + {_grafanaResourceId = If( json?.PropertyT("grafanaResourceId"), out var __jsonGrafanaResourceId) ? (string)__jsonGrafanaResourceId : (string)_grafanaResourceId;} + {_trialStartAt = If( json?.PropertyT("trialStartAt"), out var __jsonTrialStartAt) ? global::System.DateTime.TryParse((string)__jsonTrialStartAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonTrialStartAtValue) ? __jsonTrialStartAtValue : _trialStartAt : _trialStartAt;} + {_trialEndAt = If( json?.PropertyT("trialEndAt"), out var __jsonTrialEndAt) ? global::System.DateTime.TryParse((string)__jsonTrialEndAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonTrialEndAtValue) ? __jsonTrialEndAtValue : _trialEndAt : _trialEndAt;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._availablePromotion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._availablePromotion.ToString()) : null, "availablePromotion" ,container.Add ); + AddIf( null != (((object)this._grafanaResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._grafanaResourceId.ToString()) : null, "grafanaResourceId" ,container.Add ); + AddIf( null != this._trialStartAt ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._trialStartAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "trialStartAt" ,container.Add ); + AddIf( null != this._trialEndAt ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._trialEndAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "trialEndAt" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..06d1a08c877 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..7012cf55bc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..aecaa4060ad --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationDisplay()); set => this._display = value; } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for ActionType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.ActionType { get => this._actionType; set { {_actionType = value;} } } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Description = value ?? null; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Operation = value ?? null; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Provider = value ?? null; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)Display).Resource = value ?? null; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.Dashboard.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..9352065b5f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperation. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperation. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..0724f563ec5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..ab3dee7ed1e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..d059eabb8cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..142b84206db --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..eaba93f136f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..1b9bce25d02 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..c0dc598a57e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..085e9ef158c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.PowerShell.cs new file mode 100644 index 00000000000..0cb46853ec6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The private endpoint resource. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointTypeConverter))] + public partial class PrivateEndpoint + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateEndpoint DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpoint(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpoint(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpoint(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)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 PrivateEndpoint(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)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.Dashboard.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 private endpoint resource. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointTypeConverter))] + public partial interface IPrivateEndpoint + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.TypeConverter.cs new file mode 100644 index 00000000000..e37ea4200e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateEndpoint ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpoint.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpoint.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpoint.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.cs new file mode 100644 index 00000000000..83c28b17cba --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The private endpoint resource. + public partial class PrivateEndpoint : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal + { + + /// Backing field for property. + private string _id; + + /// The resource identifier of the private endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal.Id { get => this._id; set { {_id = value;} } } + + /// Creates an new instance. + public PrivateEndpoint() + { + + } + } + /// The private endpoint resource. + public partial interface IPrivateEndpoint : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The resource identifier of the private endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The resource identifier of the private endpoint", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + + } + /// The private endpoint resource. + internal partial interface IPrivateEndpointInternal + + { + /// The resource identifier of the private endpoint + string Id { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.json.cs new file mode 100644 index 00000000000..98ef97fccc6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpoint.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The private endpoint resource. + public partial class PrivateEndpoint + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateEndpoint(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpoint(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.PowerShell.cs new file mode 100644 index 00000000000..bf9a40a8f1d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The Private Endpoint Connection resource. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionTypeConverter))] + public partial class PrivateEndpointConnection + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateEndpointConnection DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnection(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnection(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnection(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.Dashboard.Models.IPrivateEndpointConnectionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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 PrivateEndpointConnection(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.Dashboard.Models.IPrivateEndpointConnectionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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.Dashboard.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 Private Endpoint Connection resource. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionTypeConverter))] + public partial interface IPrivateEndpointConnection + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.TypeConverter.cs new file mode 100644 index 00000000000..f2142032032 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateEndpointConnection ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnection.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnection.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.cs new file mode 100644 index 00000000000..1a279e57cc2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.cs @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The Private Endpoint Connection resource. + public partial class PrivateEndpointConnection : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ProxyResource(); + + /// The private endpoint connection group ids. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List GroupId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).GroupId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).GroupId = value ?? null /* arrayOf */; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for PrivateEndpoint + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal.PrivateEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateEndpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateEndpoint = value ?? null /* model class */; } + + /// Internal Acessors for PrivateEndpointId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal.PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateEndpointId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateEndpointId = value ?? null; } + + /// Internal Acessors for PrivateLinkServiceConnectionState + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal.PrivateLinkServiceConnectionState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionState = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name; } + + /// The resource identifier of the private endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateEndpointId; } + + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionStateActionsRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionStateActionsRequired = value ?? null; } + + /// The reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionStateDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionStateDescription = value ?? null; } + + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionStateStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).PrivateLinkServiceConnectionStateStatus = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties _property; + + /// Resource properties. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionProperties()); set => this._property = value; } + + /// The provisioning state of the private endpoint connection resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public PrivateEndpointConnection() + { + + } + + /// 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.Dashboard.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// The Private Endpoint Connection resource. + public partial interface IPrivateEndpointConnection : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource + { + /// The private endpoint connection group ids. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private endpoint connection group ids.", + SerializedName = @"groupIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List GroupId { get; set; } + /// The resource identifier of the private endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The resource identifier of the private endpoint", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointId { get; } + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A message indicating if changes on the service provider require any updates on the consumer.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// The reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The reason for approval/rejection of the connection.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// The provisioning state of the private endpoint connection resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the private endpoint connection resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Succeeded", "Creating", "Deleting", "Failed")] + string ProvisioningState { get; } + + } + /// The Private Endpoint Connection resource. + internal partial interface IPrivateEndpointConnectionInternal : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResourceInternal + { + /// The private endpoint connection group ids. + System.Collections.Generic.List GroupId { get; set; } + /// The resource of private end point. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint PrivateEndpoint { get; set; } + /// The resource identifier of the private endpoint + string PrivateEndpointId { get; set; } + /// + /// A collection of information about the state of the connection between service consumer and provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get; set; } + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// The reason for approval/rejection of the connection. + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// Resource properties. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties Property { get; set; } + /// The provisioning state of the private endpoint connection resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Succeeded", "Creating", "Deleting", "Failed")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.json.cs new file mode 100644 index 00000000000..01cdc5dcf9e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnection.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The Private Endpoint Connection resource. + public partial class PrivateEndpointConnection + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateEndpointConnection(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnection(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionProperties.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.PowerShell.cs new file mode 100644 index 00000000000..9a9bf2d0775 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The response of a PrivateEndpointConnection list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionListResultTypeConverter))] + public partial class PrivateEndpointConnectionListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateEndpointConnectionListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionListResult(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.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)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 PrivateEndpointConnectionListResult(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.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal)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.Dashboard.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 PrivateEndpointConnection list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionListResultTypeConverter))] + public partial interface IPrivateEndpointConnectionListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.TypeConverter.cs new file mode 100644 index 00000000000..8f3121769d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateEndpointConnectionListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.cs new file mode 100644 index 00000000000..173f78071df --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The response of a PrivateEndpointConnection list operation. + public partial class PrivateEndpointConnectionListResult : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The PrivateEndpointConnection items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PrivateEndpointConnectionListResult() + { + + } + } + /// The response of a PrivateEndpointConnection list operation. + public partial interface IPrivateEndpointConnectionListResult : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 PrivateEndpointConnection items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The PrivateEndpointConnection items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnection) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a PrivateEndpointConnection list operation. + internal partial interface IPrivateEndpointConnectionListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The PrivateEndpointConnection items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.json.cs new file mode 100644 index 00000000000..f70233bf7bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The response of a PrivateEndpointConnection list operation. + public partial class PrivateEndpointConnectionListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionListResult(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IPrivateEndpointConnection) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointConnection.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.PowerShell.cs new file mode 100644 index 00000000000..d53d8977090 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.PowerShell.cs @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Properties of the PrivateEndpointConnectProperties. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionPropertiesTypeConverter))] + public partial class PrivateEndpointConnectionProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateEndpointConnectionProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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 PrivateEndpointConnectionProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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.Dashboard.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 PrivateEndpointConnectProperties. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionPropertiesTypeConverter))] + public partial interface IPrivateEndpointConnectionProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.TypeConverter.cs new file mode 100644 index 00000000000..ea57c99cef8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateEndpointConnectionProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.cs new file mode 100644 index 00000000000..7e7396d2de7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.cs @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties of the PrivateEndpointConnectProperties. + public partial class PrivateEndpointConnectionProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _groupId; + + /// The private endpoint connection group ids. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List GroupId { get => this._groupId; set => this._groupId = value; } + + /// Internal Acessors for PrivateEndpoint + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal.PrivateEndpoint { get => (this._privateEndpoint = this._privateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpoint()); set { {_privateEndpoint = value;} } } + + /// Internal Acessors for PrivateEndpointId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal.PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)PrivateEndpoint).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)PrivateEndpoint).Id = value ?? null; } + + /// Internal Acessors for PrivateLinkServiceConnectionState + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal.PrivateLinkServiceConnectionState { get => (this._privateLinkServiceConnectionState = this._privateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionState()); set { {_privateLinkServiceConnectionState = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint _privateEndpoint; + + /// The resource of private end point. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint PrivateEndpoint { get => (this._privateEndpoint = this._privateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpoint()); set => this._privateEndpoint = value; } + + /// The resource identifier of the private endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointInternal)PrivateEndpoint).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState _privateLinkServiceConnectionState; + + /// + /// A collection of information about the state of the connection between service consumer and provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get => (this._privateLinkServiceConnectionState = this._privateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionState()); set => this._privateLinkServiceConnectionState = value; } + + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).ActionsRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).ActionsRequired = value ?? null; } + + /// The reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Description = value ?? null; } + + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Status = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state of the private endpoint connection resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Creates an new instance. + public PrivateEndpointConnectionProperties() + { + + } + } + /// Properties of the PrivateEndpointConnectProperties. + public partial interface IPrivateEndpointConnectionProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The private endpoint connection group ids. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private endpoint connection group ids.", + SerializedName = @"groupIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List GroupId { get; set; } + /// The resource identifier of the private endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The resource identifier of the private endpoint", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointId { get; } + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A message indicating if changes on the service provider require any updates on the consumer.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// The reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The reason for approval/rejection of the connection.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// The provisioning state of the private endpoint connection resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the private endpoint connection resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Succeeded", "Creating", "Deleting", "Failed")] + string ProvisioningState { get; } + + } + /// Properties of the PrivateEndpointConnectProperties. + internal partial interface IPrivateEndpointConnectionPropertiesInternal + + { + /// The private endpoint connection group ids. + System.Collections.Generic.List GroupId { get; set; } + /// The resource of private end point. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpoint PrivateEndpoint { get; set; } + /// The resource identifier of the private endpoint + string PrivateEndpointId { get; set; } + /// + /// A collection of information about the state of the connection between service consumer and provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get; set; } + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// The reason for approval/rejection of the connection. + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// The provisioning state of the private endpoint connection resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Succeeded", "Creating", "Deleting", "Failed")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.json.cs new file mode 100644 index 00000000000..6e081b2234b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProperties.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties of the PrivateEndpointConnectProperties. + public partial class PrivateEndpointConnectionProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateEndpointConnectionProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionProperties(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_privateEndpoint = If( json?.PropertyT("privateEndpoint"), out var __jsonPrivateEndpoint) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateEndpoint.FromJson(__jsonPrivateEndpoint) : _privateEndpoint;} + {_privateLinkServiceConnectionState = If( json?.PropertyT("privateLinkServiceConnectionState"), out var __jsonPrivateLinkServiceConnectionState) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkServiceConnectionState.FromJson(__jsonPrivateLinkServiceConnectionState) : _privateLinkServiceConnectionState;} + {_groupId = If( json?.PropertyT("groupIds"), out var __jsonGroupIds) ? If( __jsonGroupIds as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _groupId;} + {_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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._privateEndpoint ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._privateEndpoint.ToJson(null,serializationMode) : null, "privateEndpoint" ,container.Add ); + AddIf( null != this._privateLinkServiceConnectionState ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._privateLinkServiceConnectionState.ToJson(null,serializationMode) : null, "privateLinkServiceConnectionState" ,container.Add ); + if (null != this._groupId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._groupId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("groupIds",__w); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.PowerShell.cs new file mode 100644 index 00000000000..848bb85457f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.PowerShell.cs @@ -0,0 +1,274 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// A private link resource + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceTypeConverter))] + public partial class PrivateLinkResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateLinkResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkResource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkResource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkResource(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.Dashboard.Models.IPrivateLinkResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourcePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredZoneName, __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 PrivateLinkResource(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.Dashboard.Models.IPrivateLinkResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourcePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal)this).RequiredZoneName, __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.Dashboard.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 private link resource + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceTypeConverter))] + public partial interface IPrivateLinkResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.TypeConverter.cs new file mode 100644 index 00000000000..8eb4cd8006b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateLinkResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkResource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.cs new file mode 100644 index 00000000000..947a7f225bd --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// A private link resource + public partial class PrivateLinkResource : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ProxyResource(); + + /// The private link resource group id. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string GroupId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).GroupId; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for GroupId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal.GroupId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).GroupId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).GroupId = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for RequiredMember + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceInternal.RequiredMember { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredMember; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredMember = value ?? null /* arrayOf */; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties _property; + + /// Resource properties. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).ProvisioningState; } + + /// The private link resource required member names. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RequiredMember { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredMember; } + + /// The private link resource Private link DNS zone name. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RequiredZoneName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredZoneName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredZoneName = value ?? null /* arrayOf */; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public PrivateLinkResource() + { + + } + + /// 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.Dashboard.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// A private link resource + public partial interface IPrivateLinkResource : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource + { + /// The private link resource group id. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private link resource group id.", + SerializedName = @"groupId", + PossibleTypes = new [] { typeof(string) })] + string GroupId { get; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// The private link resource required member names. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private link resource required member names.", + SerializedName = @"requiredMembers", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredMember { get; } + /// The private link resource Private link DNS zone name. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private link resource Private link DNS zone name.", + SerializedName = @"requiredZoneNames", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredZoneName { get; set; } + + } + /// A private link resource + internal partial interface IPrivateLinkResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResourceInternal + { + /// The private link resource group id. + string GroupId { get; set; } + /// Resource properties. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// The private link resource required member names. + System.Collections.Generic.List RequiredMember { get; set; } + /// The private link resource Private link DNS zone name. + System.Collections.Generic.List RequiredZoneName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.json.cs new file mode 100644 index 00000000000..471dc8ce040 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResource.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// A private link resource + public partial class PrivateLinkResource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateLinkResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkResource(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceProperties.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.PowerShell.cs new file mode 100644 index 00000000000..9db138e6812 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The response of a PrivateLinkResource list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceListResultTypeConverter))] + public partial class PrivateLinkResourceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateLinkResourceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkResourceListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkResourceListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkResourceListResult(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.Dashboard.Models.IPrivateLinkResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal)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 PrivateLinkResourceListResult(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.Dashboard.Models.IPrivateLinkResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal)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.Dashboard.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 PrivateLinkResource list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceListResultTypeConverter))] + public partial interface IPrivateLinkResourceListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.TypeConverter.cs new file mode 100644 index 00000000000..57eac807487 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkResourceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateLinkResourceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkResourceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkResourceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkResourceListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.cs new file mode 100644 index 00000000000..4b88b48343b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The response of a PrivateLinkResource list operation. + public partial class PrivateLinkResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The PrivateLinkResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PrivateLinkResourceListResult() + { + + } + } + /// The response of a PrivateLinkResource list operation. + public partial interface IPrivateLinkResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 PrivateLinkResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The PrivateLinkResource items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResource) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a PrivateLinkResource list operation. + internal partial interface IPrivateLinkResourceListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The PrivateLinkResource items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.json.cs new file mode 100644 index 00000000000..a5a57f8ab94 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The response of a PrivateLinkResource list operation. + public partial class PrivateLinkResourceListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateLinkResourceListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkResourceListResult(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IPrivateLinkResource) (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.PrivateLinkResource.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.PowerShell.cs new file mode 100644 index 00000000000..6d20e9ece08 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Properties of a private link resource. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourcePropertiesTypeConverter))] + public partial class PrivateLinkResourceProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateLinkResourceProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkResourceProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkResourceProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkResourceProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName, __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 PrivateLinkResourceProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName, __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.Dashboard.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 a private link resource. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourcePropertiesTypeConverter))] + public partial interface IPrivateLinkResourceProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.TypeConverter.cs new file mode 100644 index 00000000000..03661a4118a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkResourcePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateLinkResourceProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkResourceProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkResourceProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkResourceProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.cs new file mode 100644 index 00000000000..2b90578393f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties of a private link resource. + public partial class PrivateLinkResourceProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal + { + + /// Backing field for property. + private string _groupId; + + /// The private link resource group id. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string GroupId { get => this._groupId; } + + /// Internal Acessors for GroupId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal.GroupId { get => this._groupId; set { {_groupId = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for RequiredMember + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourcePropertiesInternal.RequiredMember { get => this._requiredMember; set { {_requiredMember = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private System.Collections.Generic.List _requiredMember; + + /// The private link resource required member names. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List RequiredMember { get => this._requiredMember; } + + /// Backing field for property. + private System.Collections.Generic.List _requiredZoneName; + + /// The private link resource Private link DNS zone name. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Collections.Generic.List RequiredZoneName { get => this._requiredZoneName; set => this._requiredZoneName = value; } + + /// Creates an new instance. + public PrivateLinkResourceProperties() + { + + } + } + /// Properties of a private link resource. + public partial interface IPrivateLinkResourceProperties : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The private link resource group id. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private link resource group id.", + SerializedName = @"groupId", + PossibleTypes = new [] { typeof(string) })] + string GroupId { get; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; } + /// The private link resource required member names. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The private link resource required member names.", + SerializedName = @"requiredMembers", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredMember { get; } + /// The private link resource Private link DNS zone name. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private link resource Private link DNS zone name.", + SerializedName = @"requiredZoneNames", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredZoneName { get; set; } + + } + /// Properties of a private link resource. + internal partial interface IPrivateLinkResourcePropertiesInternal + + { + /// The private link resource group id. + string GroupId { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "NotSpecified")] + string ProvisioningState { get; set; } + /// The private link resource required member names. + System.Collections.Generic.List RequiredMember { get; set; } + /// The private link resource Private link DNS zone name. + System.Collections.Generic.List RequiredZoneName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.json.cs new file mode 100644 index 00000000000..445db2d9cda --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.json.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Properties of a private link resource. + public partial class PrivateLinkResourceProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkResourceProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateLinkResourceProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkResourceProperties(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_groupId = If( json?.PropertyT("groupId"), out var __jsonGroupId) ? (string)__jsonGroupId : (string)_groupId;} + {_requiredMember = If( json?.PropertyT("requiredMembers"), out var __jsonRequiredMembers) ? If( __jsonRequiredMembers as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _requiredMember;} + {_requiredZoneName = If( json?.PropertyT("requiredZoneNames"), out var __jsonRequiredZoneNames) ? If( __jsonRequiredZoneNames as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(string) (__p is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString __o ? (string)(__o.ToString()) : null)) ))() : null : _requiredZoneName;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._groupId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._groupId.ToString()) : null, "groupId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._requiredMember) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __x in this._requiredMember ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("requiredMembers",__w); + } + } + if (null != this._requiredZoneName) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.XNodeArray(); + foreach( var __s in this._requiredZoneName ) + { + AddIf(null != (((object)__s)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(__s.ToString()) : null ,__r.Add); + } + container.Add("requiredZoneNames",__r); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.PowerShell.cs new file mode 100644 index 00000000000..90662bf4606 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.PowerShell.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A collection of information about the state of the connection between service consumer and provider. + /// + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceConnectionStateTypeConverter))] + public partial class PrivateLinkServiceConnectionState + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IPrivateLinkServiceConnectionState DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkServiceConnectionState(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkServiceConnectionState(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkServiceConnectionState(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired = (string) content.GetValueForProperty("ActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired, 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 PrivateLinkServiceConnectionState(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired = (string) content.GetValueForProperty("ActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired, 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.Dashboard.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 collection of information about the state of the connection between service consumer and provider. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceConnectionStateTypeConverter))] + public partial interface IPrivateLinkServiceConnectionState + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.TypeConverter.cs new file mode 100644 index 00000000000..9abffe9b04a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkServiceConnectionStateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IPrivateLinkServiceConnectionState ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkServiceConnectionState.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkServiceConnectionState.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkServiceConnectionState.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.cs new file mode 100644 index 00000000000..cdf3e827d0b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// A collection of information about the state of the connection between service consumer and provider. + /// + public partial class PrivateLinkServiceConnectionState : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionStateInternal + { + + /// Backing field for property. + private string _actionsRequired; + + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ActionsRequired { get => this._actionsRequired; set => this._actionsRequired = value; } + + /// Backing field for property. + private string _description; + + /// The reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _status; + + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// Creates an new instance. + public PrivateLinkServiceConnectionState() + { + + } + } + /// A collection of information about the state of the connection between service consumer and provider. + public partial interface IPrivateLinkServiceConnectionState : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A message indicating if changes on the service provider require any updates on the consumer.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string ActionsRequired { get; set; } + /// The reason for approval/rejection of the connection. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The reason for approval/rejection of the connection.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected")] + string Status { get; set; } + + } + /// A collection of information about the state of the connection between service consumer and provider. + internal partial interface IPrivateLinkServiceConnectionStateInternal + + { + /// + /// A message indicating if changes on the service provider require any updates on the consumer. + /// + string ActionsRequired { get; set; } + /// The reason for approval/rejection of the connection. + string Description { get; set; } + /// + /// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Pending", "Approved", "Rejected")] + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.json.cs new file mode 100644 index 00000000000..91428a9831c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// A collection of information about the state of the connection between service consumer and provider. + /// + public partial class PrivateLinkServiceConnectionState + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IPrivateLinkServiceConnectionState FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new PrivateLinkServiceConnectionState(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkServiceConnectionState(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_actionsRequired = If( json?.PropertyT("actionsRequired"), out var __jsonActionsRequired) ? (string)__jsonActionsRequired : (string)_actionsRequired;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._actionsRequired)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._actionsRequired.ToString()) : null, "actionsRequired" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs new file mode 100644 index 00000000000..0f977a8900d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs new file mode 100644 index 00000000000..4ed01c40e1a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.cs new file mode 100644 index 00000000000..114499c915d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ProxyResource.json.cs new file mode 100644 index 00000000000..e99380cb0fa --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..0ebc084c711 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..c83d1772930 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..f34296b7833 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Resource.cs @@ -0,0 +1,255 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// 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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..60792021d67 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.PowerShell.cs new file mode 100644 index 00000000000..40c02267cd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Represents the SKU of a resource. + [System.ComponentModel.TypeConverter(typeof(ResourceSkuTypeConverter))] + public partial class ResourceSku + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IResourceSku DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceSku(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceSku(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceSku(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.Dashboard.Models.IResourceSkuInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal)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 ResourceSku(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.Dashboard.Models.IResourceSkuInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal)this).Name, 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.Dashboard.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(); + } + } + /// Represents the SKU of a resource. + [System.ComponentModel.TypeConverter(typeof(ResourceSkuTypeConverter))] + public partial interface IResourceSku + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.TypeConverter.cs new file mode 100644 index 00000000000..eb13b2d9939 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceSkuTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IResourceSku ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceSku.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceSku.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceSku.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.cs new file mode 100644 index 00000000000..da2cd4a3de1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Represents the SKU of a resource. + public partial class ResourceSku : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSkuInternal + { + + /// Backing field for property. + private string _name; + + /// The name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public ResourceSku() + { + + } + } + /// Represents the SKU of a resource. + public partial interface IResourceSku : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Represents the SKU of a resource. + internal partial interface IResourceSkuInternal + + { + /// The name of the SKU. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.json.cs new file mode 100644 index 00000000000..65a9dea9cde --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/ResourceSku.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Represents the SKU of a resource. + public partial class ResourceSku + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceSku FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new ResourceSku(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceSku(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.PowerShell.cs new file mode 100644 index 00000000000..7e34e63de82 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// SaaS subscription details of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(SaasSubscriptionDetailsTypeConverter))] + public partial class SaasSubscriptionDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.ISaasSubscriptionDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SaasSubscriptionDetails(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SaasSubscriptionDetails(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SaasSubscriptionDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Term")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).Term = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm) content.GetValueForProperty("Term",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).Term, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTermTypeConverter.ConvertFrom); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermStartDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermStartDate = (global::System.DateTime?) content.GetValueForProperty("TermStartDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermStartDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TermEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermEndDate = (global::System.DateTime?) content.GetValueForProperty("TermEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermEndDate, (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 SaasSubscriptionDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Term")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).Term = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm) content.GetValueForProperty("Term",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).Term, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTermTypeConverter.ConvertFrom); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermStartDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermStartDate = (global::System.DateTime?) content.GetValueForProperty("TermStartDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermStartDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("TermEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermEndDate = (global::System.DateTime?) content.GetValueForProperty("TermEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal)this).TermEndDate, (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.Dashboard.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(); + } + } + /// SaaS subscription details of a Grafana instance + [System.ComponentModel.TypeConverter(typeof(SaasSubscriptionDetailsTypeConverter))] + public partial interface ISaasSubscriptionDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.TypeConverter.cs new file mode 100644 index 00000000000..aad7bf93a63 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SaasSubscriptionDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ISaasSubscriptionDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SaasSubscriptionDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SaasSubscriptionDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SaasSubscriptionDetails.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.cs new file mode 100644 index 00000000000..3aa18e29478 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// SaaS subscription details of a Grafana instance + public partial class SaasSubscriptionDetails : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal + { + + /// Internal Acessors for Term + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetailsInternal.Term { get => (this._term = this._term ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTerm()); set { {_term = value;} } } + + /// Backing field for property. + private string _offerId; + + /// The offer Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string OfferId { get => this._offerId; set => this._offerId = value; } + + /// Backing field for property. + private string _planId; + + /// The plan Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PlanId { get => this._planId; set => this._planId = value; } + + /// Backing field for property. + private string _publisherId; + + /// The publisher Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string PublisherId { get => this._publisherId; set => this._publisherId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm _term; + + /// The billing term of the SaaS Subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm Term { get => (this._term = this._term ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTerm()); set => this._term = value; } + + /// The date and time in UTC of when the billing term ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? TermEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)Term).EndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)Term).EndDate = value ?? default(global::System.DateTime); } + + /// The date and time in UTC of when the billing term starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public global::System.DateTime? TermStartDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)Term).StartDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)Term).StartDate = value ?? default(global::System.DateTime); } + + /// The unit of the billing term. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inlined)] + public string TermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)Term).TermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)Term).TermUnit = value ?? null; } + + /// Creates an new instance. + public SaasSubscriptionDetails() + { + + } + } + /// SaaS subscription details of a Grafana instance + public partial interface ISaasSubscriptionDetails : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The offer Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The offer Id of the SaaS subscription.", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferId { get; set; } + /// The plan Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The plan Id of the SaaS subscription.", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string PlanId { get; set; } + /// The publisher Id of the SaaS subscription. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The publisher Id of the SaaS subscription.", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string PublisherId { get; set; } + /// The date and time in UTC of when the billing term ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the billing term ends.", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TermEndDate { get; set; } + /// The date and time in UTC of when the billing term starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the billing term starts.", + SerializedName = @"startDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TermStartDate { get; set; } + /// The unit of the billing term. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The unit of the billing term.", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string TermUnit { get; set; } + + } + /// SaaS subscription details of a Grafana instance + internal partial interface ISaasSubscriptionDetailsInternal + + { + /// The offer Id of the SaaS subscription. + string OfferId { get; set; } + /// The plan Id of the SaaS subscription. + string PlanId { get; set; } + /// The publisher Id of the SaaS subscription. + string PublisherId { get; set; } + /// The billing term of the SaaS Subscription. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm Term { get; set; } + /// The date and time in UTC of when the billing term ends. + global::System.DateTime? TermEndDate { get; set; } + /// The date and time in UTC of when the billing term starts. + global::System.DateTime? TermStartDate { get; set; } + /// The unit of the billing term. + string TermUnit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.json.cs new file mode 100644 index 00000000000..c9fdb756315 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SaasSubscriptionDetails.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// SaaS subscription details of a Grafana instance + public partial class SaasSubscriptionDetails + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISaasSubscriptionDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new SaasSubscriptionDetails(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal SaasSubscriptionDetails(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_term = If( json?.PropertyT("term"), out var __jsonTerm) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SubscriptionTerm.FromJson(__jsonTerm) : _term;} + {_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;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._term ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) this._term.ToJson(null,serializationMode) : null, "term" ,container.Add ); + AddIf( null != (((object)this._planId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._planId.ToString()) : null, "planId" ,container.Add ); + AddIf( null != (((object)this._offerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._offerId.ToString()) : null, "offerId" ,container.Add ); + AddIf( null != (((object)this._publisherId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._publisherId.ToString()) : null, "publisherId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.PowerShell.cs new file mode 100644 index 00000000000..07bccbe593d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Grafana security settings + [System.ComponentModel.TypeConverter(typeof(SecurityTypeConverter))] + public partial class Security + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.ISecurity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Security(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Security(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Security(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal)this).CsrfAlwaysCheck = (bool?) content.GetValueForProperty("CsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal)this).CsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Security(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CsrfAlwaysCheck")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal)this).CsrfAlwaysCheck = (bool?) content.GetValueForProperty("CsrfAlwaysCheck",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal)this).CsrfAlwaysCheck, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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(); + } + } + /// Grafana security settings + [System.ComponentModel.TypeConverter(typeof(SecurityTypeConverter))] + public partial interface ISecurity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.TypeConverter.cs new file mode 100644 index 00000000000..0010e3e39a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SecurityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ISecurity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Security.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Security.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Security.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/Security.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.cs new file mode 100644 index 00000000000..589a3283e47 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana security settings + public partial class Security : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurityInternal + { + + /// Backing field for property. + private bool? _csrfAlwaysCheck; + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? CsrfAlwaysCheck { get => this._csrfAlwaysCheck; set => this._csrfAlwaysCheck = value; } + + /// Creates an new instance. + public Security() + { + + } + } + /// Grafana security settings + public partial interface ISecurity : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(bool) })] + bool? CsrfAlwaysCheck { get; set; } + + } + /// Grafana security settings + internal partial interface ISecurityInternal + + { + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + bool? CsrfAlwaysCheck { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.json.cs new file mode 100644 index 00000000000..64c09a633d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Security.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana security settings + public partial class Security + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISecurity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new Security(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Security(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_csrfAlwaysCheck = If( json?.PropertyT("csrfAlwaysCheck"), out var __jsonCsrfAlwaysCheck) ? (bool?)__jsonCsrfAlwaysCheck : _csrfAlwaysCheck;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._csrfAlwaysCheck ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._csrfAlwaysCheck) : null, "csrfAlwaysCheck" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.PowerShell.cs new file mode 100644 index 00000000000..adb0ec2b8db --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.PowerShell.cs @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + [System.ComponentModel.TypeConverter(typeof(SmtpTypeConverter))] + public partial class Smtp + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.ISmtp DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Smtp(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Smtp(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Smtp(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Enabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Enabled = (bool?) content.GetValueForProperty("Enabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Enabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Host")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Host = (string) content.GetValueForProperty("Host",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Host, global::System.Convert.ToString); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).User = (string) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).User, global::System.Convert.ToString); + } + if (content.Contains("Password")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Password = (System.Security.SecureString) content.GetValueForProperty("Password",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Password, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("FromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromAddress = (string) content.GetValueForProperty("FromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromAddress, global::System.Convert.ToString); + } + if (content.Contains("FromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromName = (string) content.GetValueForProperty("FromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromName, global::System.Convert.ToString); + } + if (content.Contains("StartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).StartTlsPolicy = (string) content.GetValueForProperty("StartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).StartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).SkipVerify = (bool?) content.GetValueForProperty("SkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).SkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Smtp(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Enabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Enabled = (bool?) content.GetValueForProperty("Enabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Enabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Host")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Host = (string) content.GetValueForProperty("Host",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Host, global::System.Convert.ToString); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).User = (string) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).User, global::System.Convert.ToString); + } + if (content.Contains("Password")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Password = (System.Security.SecureString) content.GetValueForProperty("Password",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).Password, (object ss) => (System.Security.SecureString)ss); + } + if (content.Contains("FromAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromAddress = (string) content.GetValueForProperty("FromAddress",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromAddress, global::System.Convert.ToString); + } + if (content.Contains("FromName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromName = (string) content.GetValueForProperty("FromName",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).FromName, global::System.Convert.ToString); + } + if (content.Contains("StartTlsPolicy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).StartTlsPolicy = (string) content.GetValueForProperty("StartTlsPolicy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).StartTlsPolicy, global::System.Convert.ToString); + } + if (content.Contains("SkipVerify")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).SkipVerify = (bool?) content.GetValueForProperty("SkipVerify",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal)this).SkipVerify, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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(); + } + } + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + [System.ComponentModel.TypeConverter(typeof(SmtpTypeConverter))] + public partial interface ISmtp + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.TypeConverter.cs new file mode 100644 index 00000000000..6c91a0a16b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SmtpTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ISmtp ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Smtp.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Smtp.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Smtp.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/Smtp.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.cs new file mode 100644 index 00000000000..8ee371b6dd6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.cs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + public partial class Smtp : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtpInternal + { + + /// Backing field for property. + private bool? _enabled; + + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? Enabled { get => this._enabled; set => this._enabled = value; } + + /// Backing field for property. + private string _fromAddress; + + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string FromAddress { get => this._fromAddress; set => this._fromAddress = value; } + + /// Backing field for property. + private string _fromName; + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string FromName { get => this._fromName; set => this._fromName = value; } + + /// Backing field for property. + private string _host; + + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Host { get => this._host; set => this._host = value; } + + /// Backing field for property. + private System.Security.SecureString _password; + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public System.Security.SecureString Password { get => this._password; set => this._password = value; } + + /// Backing field for property. + private bool? _skipVerify; + + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? SkipVerify { get => this._skipVerify; set => this._skipVerify = value; } + + /// Backing field for property. + private string _startTlsPolicy; + + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string StartTlsPolicy { get => this._startTlsPolicy; set => this._startTlsPolicy = value; } + + /// Backing field for property. + private string _user; + + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string User { get => this._user; set => this._user = value; } + + /// Creates an new instance. + public Smtp() + { + + } + } + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + public partial interface ISmtp : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Enable this to allow Grafana to send email. Default is false + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(bool) })] + bool? Enabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Address used when sending out emails + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + string FromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification"" + https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + string FromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + string Host { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + System.Security.SecureString Password { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Verify SSL for SMTP server. Default is false + https://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(bool) })] + bool? SkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The StartTLSPolicy setting of the SMTP configuration + https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string StartTlsPolicy { get; set; } + /// User of SMTP auth + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + string User { get; set; } + + } + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + internal partial interface ISmtpInternal + + { + /// Enable this to allow Grafana to send email. Default is false + bool? Enabled { get; set; } + /// + /// Address used when sending out emails + /// https://pkg.go.dev/net/mail#Address + /// + string FromAddress { get; set; } + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification" + /// https://pkg.go.dev/net/mail#Address + /// + string FromName { get; set; } + /// SMTP server hostname with port, e.g. test.email.net:587 + string Host { get; set; } + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + System.Security.SecureString Password { get; set; } + /// + /// Verify SSL for SMTP server. Default is false + /// https://pkg.go.dev/crypto/tls#Config + /// + bool? SkipVerify { get; set; } + /// + /// The StartTLSPolicy setting of the SMTP configuration + /// https://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + string StartTlsPolicy { get; set; } + /// User of SMTP auth + string User { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.json.cs new file mode 100644 index 00000000000..8fd4779a619 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Smtp.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// + /// Email server settings. + /// https://grafana.com/docs/grafana/v9.0/setup-grafana/configure-grafana/#smtp + /// + public partial class Smtp + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISmtp FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new Smtp(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Smtp(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_enabled = If( json?.PropertyT("enabled"), out var __jsonEnabled) ? (bool?)__jsonEnabled : _enabled;} + {_host = If( json?.PropertyT("host"), out var __jsonHost) ? (string)__jsonHost : (string)_host;} + {_user = If( json?.PropertyT("user"), out var __jsonUser) ? (string)__jsonUser : (string)_user;} + {_password = If( json?.PropertyT("password"), out var __jsonPassword) ? new System.Net.NetworkCredential("",(string)__jsonPassword).SecurePassword : _password;} + {_fromAddress = If( json?.PropertyT("fromAddress"), out var __jsonFromAddress) ? (string)__jsonFromAddress : (string)_fromAddress;} + {_fromName = If( json?.PropertyT("fromName"), out var __jsonFromName) ? (string)__jsonFromName : (string)_fromName;} + {_startTlsPolicy = If( json?.PropertyT("startTLSPolicy"), out var __jsonStartTlsPolicy) ? (string)__jsonStartTlsPolicy : (string)_startTlsPolicy;} + {_skipVerify = If( json?.PropertyT("skipVerify"), out var __jsonSkipVerify) ? (bool?)__jsonSkipVerify : _skipVerify;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._enabled ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._enabled) : null, "enabled" ,container.Add ); + AddIf( null != (((object)this._host)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._host.ToString()) : null, "host" ,container.Add ); + AddIf( null != (((object)this._user)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._user.ToString()) : null, "user" ,container.Add ); + AddIf( null != (((object)this._password)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(System.Runtime.InteropServices.Marshal.PtrToStringBSTR(System.Runtime.InteropServices.Marshal.SecureStringToBSTR(this._password))) : null, "password" ,container.Add ); + AddIf( null != (((object)this._fromAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._fromAddress.ToString()) : null, "fromAddress" ,container.Add ); + AddIf( null != (((object)this._fromName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._fromName.ToString()) : null, "fromName" ,container.Add ); + AddIf( null != (((object)this._startTlsPolicy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._startTlsPolicy.ToString()) : null, "startTLSPolicy" ,container.Add ); + AddIf( null != this._skipVerify ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._skipVerify) : null, "skipVerify" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.PowerShell.cs new file mode 100644 index 00000000000..928fb5fa16a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Grafana Snapshots settings + [System.ComponentModel.TypeConverter(typeof(SnapshotsTypeConverter))] + public partial class Snapshots + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.ISnapshots DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Snapshots(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Snapshots(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Snapshots(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal)this).ExternalEnabled = (bool?) content.GetValueForProperty("ExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal)this).ExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Snapshots(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ExternalEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal)this).ExternalEnabled = (bool?) content.GetValueForProperty("ExternalEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal)this).ExternalEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.Dashboard.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(); + } + } + /// Grafana Snapshots settings + [System.ComponentModel.TypeConverter(typeof(SnapshotsTypeConverter))] + public partial interface ISnapshots + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.TypeConverter.cs new file mode 100644 index 00000000000..9e8ac03ec29 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SnapshotsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ISnapshots ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Snapshots.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Snapshots.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Snapshots.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/Snapshots.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.cs new file mode 100644 index 00000000000..5f1d7865d34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana Snapshots settings + public partial class Snapshots : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshotsInternal + { + + /// Backing field for property. + private bool? _externalEnabled; + + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? ExternalEnabled { get => this._externalEnabled; set => this._externalEnabled = value; } + + /// Creates an new instance. + public Snapshots() + { + + } + } + /// Grafana Snapshots settings + public partial interface ISnapshots : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// Set to false to disable external snapshot publish endpoint + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? ExternalEnabled { get; set; } + + } + /// Grafana Snapshots settings + internal partial interface ISnapshotsInternal + + { + /// Set to false to disable external snapshot publish endpoint + bool? ExternalEnabled { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.json.cs new file mode 100644 index 00000000000..3be5ea1a22a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Snapshots.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana Snapshots settings + public partial class Snapshots + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISnapshots FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new Snapshots(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Snapshots(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_externalEnabled = If( json?.PropertyT("externalEnabled"), out var __jsonExternalEnabled) ? (bool?)__jsonExternalEnabled : _externalEnabled;} + 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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._externalEnabled ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._externalEnabled) : null, "externalEnabled" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.PowerShell.cs new file mode 100644 index 00000000000..9044037c43d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// The current billing term of the SaaS Subscription. + [System.ComponentModel.TypeConverter(typeof(SubscriptionTermTypeConverter))] + public partial class SubscriptionTerm + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.ISubscriptionTerm DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SubscriptionTerm(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SubscriptionTerm(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SubscriptionTerm(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("StartDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).StartDate = (global::System.DateTime?) content.GetValueForProperty("StartDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).StartDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).EndDate = (global::System.DateTime?) content.GetValueForProperty("EndDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)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 SubscriptionTerm(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("StartDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).StartDate = (global::System.DateTime?) content.GetValueForProperty("StartDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).StartDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)this).EndDate = (global::System.DateTime?) content.GetValueForProperty("EndDate",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal)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.Dashboard.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 current billing term of the SaaS Subscription. + [System.ComponentModel.TypeConverter(typeof(SubscriptionTermTypeConverter))] + public partial interface ISubscriptionTerm + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.TypeConverter.cs new file mode 100644 index 00000000000..290a8bf2124 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SubscriptionTermTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ISubscriptionTerm ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SubscriptionTerm.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SubscriptionTerm.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SubscriptionTerm.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.cs new file mode 100644 index 00000000000..b885dde443e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The current billing term of the SaaS Subscription. + public partial class SubscriptionTerm : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTermInternal + { + + /// Backing field for property. + private global::System.DateTime? _endDate; + + /// The date and time in UTC of when the billing term ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public global::System.DateTime? EndDate { get => this._endDate; set => this._endDate = value; } + + /// Backing field for property. + private global::System.DateTime? _startDate; + + /// The date and time in UTC of when the billing term starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public global::System.DateTime? StartDate { get => this._startDate; set => this._startDate = value; } + + /// Backing field for property. + private string _termUnit; + + /// The unit of the billing term. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string TermUnit { get => this._termUnit; set => this._termUnit = value; } + + /// Creates an new instance. + public SubscriptionTerm() + { + + } + } + /// The current billing term of the SaaS Subscription. + public partial interface ISubscriptionTerm : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// The date and time in UTC of when the billing term ends. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the billing term ends.", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndDate { get; set; } + /// The date and time in UTC of when the billing term starts. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The date and time in UTC of when the billing term starts.", + SerializedName = @"startDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartDate { get; set; } + /// The unit of the billing term. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The unit of the billing term.", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string TermUnit { get; set; } + + } + /// The current billing term of the SaaS Subscription. + internal partial interface ISubscriptionTermInternal + + { + /// The date and time in UTC of when the billing term ends. + global::System.DateTime? EndDate { get; set; } + /// The date and time in UTC of when the billing term starts. + global::System.DateTime? StartDate { get; set; } + /// The unit of the billing term. + string TermUnit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.json.cs new file mode 100644 index 00000000000..bedff8d275d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SubscriptionTerm.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// The current billing term of the SaaS Subscription. + public partial class SubscriptionTerm + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISubscriptionTerm FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new SubscriptionTerm(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal SubscriptionTerm(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_termUnit = If( json?.PropertyT("termUnit"), out var __jsonTermUnit) ? (string)__jsonTermUnit : (string)_termUnit;} + {_startDate = If( json?.PropertyT("startDate"), out var __jsonStartDate) ? global::System.DateTime.TryParse((string)__jsonStartDate, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartDateValue) ? __jsonStartDateValue : _startDate : _startDate;} + {_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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._termUnit)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._termUnit.ToString()) : null, "termUnit" ,container.Add ); + AddIf( null != this._startDate ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._startDate?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startDate" ,container.Add ); + AddIf( null != this._endDate ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..7125e765d3d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..920b22e5dcd --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..066f9418fc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..cdc6bd223c3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..37c1584808e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..fcf4798a143 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..7882b7562d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + 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.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags 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.Dashboard.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..cbcb598d227 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.TrackedResourceTags.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/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs new file mode 100644 index 00000000000..8506ff446f9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial class TrackedResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// 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.Dashboard.Models.ITrackedResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 TrackedResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial interface ITrackedResourceTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs new file mode 100644 index 00000000000..1bd2e72f4cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.ITrackedResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.cs new file mode 100644 index 00000000000..06f77c71624 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTagsInternal + { + + /// Creates an new instance. + public TrackedResourceTags() + { + + } + } + /// Resource tags. + public partial interface ITrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITrackedResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs new file mode 100644 index 00000000000..0a129d95fee --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.TrackedResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs new file mode 100644 index 00000000000..5327d1da4d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/TrackedResourceTags.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new TrackedResourceTags(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TrackedResourceTags(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.PowerShell.cs new file mode 100644 index 00000000000..612beb0f655 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Grafana Unified Alerting Screenshots settings + [System.ComponentModel.TypeConverter(typeof(UnifiedAlertingScreenshotsTypeConverter))] + public partial class UnifiedAlertingScreenshots + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IUnifiedAlertingScreenshots DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UnifiedAlertingScreenshots(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UnifiedAlertingScreenshots(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 UnifiedAlertingScreenshots(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal)this).CaptureEnabled = (bool?) content.GetValueForProperty("CaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal)this).CaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UnifiedAlertingScreenshots(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CaptureEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal)this).CaptureEnabled = (bool?) content.GetValueForProperty("CaptureEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal)this).CaptureEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializePSObject(content); + } + } + /// Grafana Unified Alerting Screenshots settings + [System.ComponentModel.TypeConverter(typeof(UnifiedAlertingScreenshotsTypeConverter))] + public partial interface IUnifiedAlertingScreenshots + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.TypeConverter.cs new file mode 100644 index 00000000000..608fd69bd4e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UnifiedAlertingScreenshotsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IUnifiedAlertingScreenshots ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UnifiedAlertingScreenshots.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UnifiedAlertingScreenshots.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UnifiedAlertingScreenshots.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.cs new file mode 100644 index 00000000000..6532aae98ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana Unified Alerting Screenshots settings + public partial class UnifiedAlertingScreenshots : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshotsInternal + { + + /// Backing field for property. + private bool? _captureEnabled; + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? CaptureEnabled { get => this._captureEnabled; set => this._captureEnabled = value; } + + /// Creates an new instance. + public UnifiedAlertingScreenshots() + { + + } + } + /// Grafana Unified Alerting Screenshots settings + public partial interface IUnifiedAlertingScreenshots : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? CaptureEnabled { get; set; } + + } + /// Grafana Unified Alerting Screenshots settings + internal partial interface IUnifiedAlertingScreenshotsInternal + + { + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + bool? CaptureEnabled { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.json.cs new file mode 100644 index 00000000000..fd146e1726b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UnifiedAlertingScreenshots.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana Unified Alerting Screenshots settings + public partial class UnifiedAlertingScreenshots + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUnifiedAlertingScreenshots FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new UnifiedAlertingScreenshots(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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._captureEnabled ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._captureEnabled) : null, "captureEnabled" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal UnifiedAlertingScreenshots(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_captureEnabled = If( json?.PropertyT("captureEnabled"), out var __jsonCaptureEnabled) ? (bool?)__jsonCaptureEnabled : _captureEnabled;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs new file mode 100644 index 00000000000..2d4cf26040f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IUserAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs new file mode 100644 index 00000000000..75f4584fb14 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IUserAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs new file mode 100644 index 00000000000..a180136f6c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentityInternal + { + + /// Backing field for property. + private string _clientId; + + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentityInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IJsonSerializable + { + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs new file mode 100644 index 00000000000..b27535a4a5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUserAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/api/Models/Users.PowerShell.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.PowerShell.cs new file mode 100644 index 00000000000..95fecc7d5bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// Grafana users settings + [System.ComponentModel.TypeConverter(typeof(UsersTypeConverter))] + public partial class Users + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.Dashboard.Models.IUsers DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Users(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Users(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 Users(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).ViewersCanEdit = (bool?) content.GetValueForProperty("ViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).ViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).EditorsCanAdmin = (bool?) content.GetValueForProperty("EditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).EditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Users(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ViewersCanEdit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).ViewersCanEdit = (bool?) content.GetValueForProperty("ViewersCanEdit",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).ViewersCanEdit, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EditorsCanAdmin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).EditorsCanAdmin = (bool?) content.GetValueForProperty("EditorsCanAdmin",((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal)this).EditorsCanAdmin, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializePSObject(content); + } + } + /// Grafana users settings + [System.ComponentModel.TypeConverter(typeof(UsersTypeConverter))] + public partial interface IUsers + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.TypeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.TypeConverter.cs new file mode 100644 index 00000000000..47c47f879bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.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.Dashboard.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UsersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.Dashboard.Models.IUsers ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Users.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Users.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Users.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Dashboard.Management.brown/target/generated/api/Models/Users.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.cs new file mode 100644 index 00000000000..0d50deb6539 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana users settings + public partial class Users : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsersInternal + { + + /// Backing field for property. + private bool? _editorsCanAdmin; + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? EditorsCanAdmin { get => this._editorsCanAdmin; set => this._editorsCanAdmin = value; } + + /// Backing field for property. + private bool? _viewersCanEdit; + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Origin(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PropertyOrigin.Owned)] + public bool? ViewersCanEdit { get => this._viewersCanEdit; set => this._viewersCanEdit = value; } + + /// Creates an new instance. + public Users() + { + + } + } + /// Grafana users settings + public partial interface IUsers : + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IJsonSerializable + { + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(bool) })] + bool? EditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(bool) })] + bool? ViewersCanEdit { get; set; } + + } + /// Grafana users settings + internal partial interface IUsersInternal + + { + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + bool? EditorsCanAdmin { get; set; } + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + bool? ViewersCanEdit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.json.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.json.cs new file mode 100644 index 00000000000..c298e141526 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/api/Models/Users.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.Dashboard.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + + /// Grafana users settings + public partial class Users + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers. + public static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IUsers FromJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json ? new Users(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.Dashboard.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._viewersCanEdit ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._viewersCanEdit) : null, "viewersCanEdit" ,container.Add ); + AddIf( null != this._editorsCanAdmin ? (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonBoolean((bool)this._editorsCanAdmin) : null, "editorsCanAdmin" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject instance to deserialize from. + internal Users(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_viewersCanEdit = If( json?.PropertyT("viewersCanEdit"), out var __jsonViewersCanEdit) ? (bool?)__jsonViewersCanEdit : _viewersCanEdit;} + {_editorsCanAdmin = If( json?.PropertyT("editorsCanAdmin"), out var __jsonEditorsCanAdmin) ? (bool?)__jsonEditorsCanAdmin : _editorsCanAdmin;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_Get.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_Get.cs new file mode 100644 index 00000000000..74b48c3dd14 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get the properties of a specific workspace for Grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardGrafana_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get the properties of a specific workspace for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardGrafana_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardGrafana_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaGet(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_GetViaIdentity.cs new file mode 100644 index 00000000000..4e4c94daf3f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get the properties of a specific workspace for Grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardGrafana_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get the properties of a specific workspace for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardGrafana_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardGrafana_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.GrafanaGetViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.GrafanaGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_List.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_List.cs new file mode 100644 index 00000000000..70b522f42e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_List.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// List all resources of workspaces for Grafana under the specified resource group. + /// + /// + /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardGrafana_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List all resources of workspaces for Grafana under the specified resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardGrafana_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafanaListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardGrafana_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafanaListResponse + /// 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.Dashboard.Models.IManagedGrafanaListResponse + 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_List1.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_List1.cs new file mode 100644 index 00000000000..03ded45839a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardGrafana_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// List all resources of workspaces for Grafana under the specified subscription. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/grafana" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardGrafana_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List all resources of workspaces for Grafana under the specified subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/grafana", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardGrafana_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafanaListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardGrafana_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaList(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafanaListResponse + /// 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.Dashboard.Models.IManagedGrafanaListResponse + 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_Get.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_Get.cs new file mode 100644 index 00000000000..6075820caf0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_Get.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get a IntegrationFabric + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardIntegrationFabric_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardIntegrationFabric_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardIntegrationFabric_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsGet(SubscriptionId, ResourceGroupName, WorkspaceName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_GetViaIdentity.cs new file mode 100644 index 00000000000..0fc1754c8dc --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get a IntegrationFabric + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardIntegrationFabric_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardIntegrationFabric_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardIntegrationFabric_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IntegrationFabricsGetViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.IntegrationFabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.IntegrationFabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IntegrationFabricsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, InputObject.IntegrationFabricName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_GetViaIdentityGrafana.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_GetViaIdentityGrafana.cs new file mode 100644 index 00000000000..1634642fde6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_GetViaIdentityGrafana.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get a IntegrationFabric + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardIntegrationFabric_GetViaIdentityGrafana")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardIntegrationFabric_GetViaIdentityGrafana : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _grafanaInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity GrafanaInputObject { get => this._grafanaInputObject; set => this._grafanaInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardIntegrationFabric_GetViaIdentityGrafana() + { + + } + + /// 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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (GrafanaInputObject?.Id != null) + { + this.GrafanaInputObject.Id += $"/integrationFabrics/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.IntegrationFabricsGetViaIdentity(GrafanaInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == GrafanaInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + await this.Client.IntegrationFabricsGet(GrafanaInputObject.SubscriptionId ?? null, GrafanaInputObject.ResourceGroupName ?? null, GrafanaInputObject.WorkspaceName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_List.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_List.cs new file mode 100644 index 00000000000..355ecd5bd11 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardIntegrationFabric_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// List IntegrationFabric resources by ManagedGrafana + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardIntegrationFabric_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List IntegrationFabric resources by ManagedGrafana")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardIntegrationFabric_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabricListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardIntegrationFabric_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsList(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabricListResponse + /// 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.Dashboard.Models.IIntegrationFabricListResponse + 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_Get.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_Get.cs new file mode 100644 index 00000000000..0044d83e6a6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_Get.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get a specific managed private endpoint of a grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardManagedPrivateEndpoint_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get a specific managed private endpoint of a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardManagedPrivateEndpoint_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardManagedPrivateEndpoint_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsGet(SubscriptionId, ResourceGroupName, WorkspaceName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_GetViaIdentity.cs new file mode 100644 index 00000000000..18cac311c17 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get a specific managed private endpoint of a grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardManagedPrivateEndpoint_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get a specific managed private endpoint of a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardManagedPrivateEndpoint_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardManagedPrivateEndpoint_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ManagedPrivateEndpointsGetViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ManagedPrivateEndpointName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ManagedPrivateEndpointName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ManagedPrivateEndpointsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, InputObject.ManagedPrivateEndpointName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_GetViaIdentityGrafana.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_GetViaIdentityGrafana.cs new file mode 100644 index 00000000000..f129efb5540 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_GetViaIdentityGrafana.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get a specific managed private endpoint of a grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardManagedPrivateEndpoint_GetViaIdentityGrafana")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get a specific managed private endpoint of a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardManagedPrivateEndpoint_GetViaIdentityGrafana : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _grafanaInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity GrafanaInputObject { get => this._grafanaInputObject; set => this._grafanaInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardManagedPrivateEndpoint_GetViaIdentityGrafana() + { + + } + + /// 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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (GrafanaInputObject?.Id != null) + { + this.GrafanaInputObject.Id += $"/managedPrivateEndpoints/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ManagedPrivateEndpointsGetViaIdentity(GrafanaInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == GrafanaInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + await this.Client.ManagedPrivateEndpointsGet(GrafanaInputObject.SubscriptionId ?? null, GrafanaInputObject.ResourceGroupName ?? null, GrafanaInputObject.WorkspaceName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_List.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_List.cs new file mode 100644 index 00000000000..b4f0cc268c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardManagedPrivateEndpoint_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// List all managed private endpoints of a grafana resource. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardManagedPrivateEndpoint_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List all managed private endpoints of a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardManagedPrivateEndpoint_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModelListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardManagedPrivateEndpoint_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsList(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModelListResponse + /// 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.Dashboard.Models.IManagedPrivateEndpointModelListResponse + 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardOperation_List.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardOperation_List.cs new file mode 100644 index 00000000000..2cbbda5f8e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboardOperation_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Microsoft.Dashboard/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboardOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/providers/Microsoft.Dashboard/operations", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboardOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboardOperation_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_Get.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_Get.cs new file mode 100644 index 00000000000..ff3048b4105 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get the properties of a specific dashboard for grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboard_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get the properties of a specific dashboard for grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboard_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("DashboardName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboard_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DashboardsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_GetViaIdentity.cs new file mode 100644 index 00000000000..839b811909b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Get the properties of a specific dashboard for grafana resource. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboard_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Get the properties of a specific dashboard for grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboard_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboard_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.DashboardsGetViaIdentity(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.DashboardName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DashboardName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.DashboardsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.DashboardName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + 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/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_List.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_List.cs new file mode 100644 index 00000000000..72c1c920e72 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// List all resources of dashboards under the specified resource group. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboard_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List all resources of dashboards under the specified resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboard_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboardListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboard_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DashboardsList(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboardListResponse + /// 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.Dashboard.Models.IManagedDashboardListResponse + 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DashboardsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_List1.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_List1.cs new file mode 100644 index 00000000000..24aebeb90b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/GetAzDashboard_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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// List all resources of dashboards under the specified subscription. + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/dashboards" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDashboard_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"List all resources of dashboards under the specified subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/dashboards", ApiVersion = "2024-11-01-preview")] + public partial class GetAzDashboard_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboardListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 GetAzDashboard_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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DashboardsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboardListResponse + /// 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.Dashboard.Models.IManagedDashboardListResponse + 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DashboardsListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/InvokeAzDashboardFetchGrafanaAvailablePlugin_Fetch.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/InvokeAzDashboardFetchGrafanaAvailablePlugin_Fetch.cs new file mode 100644 index 00000000000..8fa8ef1bd78 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/InvokeAzDashboardFetchGrafanaAvailablePlugin_Fetch.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// A synchronous resource action. + /// + /// [OpenAPI] FetchAvailablePlugins=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/fetchAvailablePlugins" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzDashboardFetchGrafanaAvailablePlugin_Fetch", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"A synchronous resource action.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/fetchAvailablePlugins", ApiVersion = "2024-11-01-preview")] + public partial class InvokeAzDashboardFetchGrafanaAvailablePlugin_Fetch : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IGrafanaAvailablePluginListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 InvokeAzDashboardFetchGrafanaAvailablePlugin_Fetch() + { + + } + + /// 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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaFetchAvailablePlugins' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaFetchAvailablePlugins(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IGrafanaAvailablePluginListResponse + /// 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.Dashboard.Models.IGrafanaAvailablePluginListResponse + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaFetchAvailablePlugins_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/InvokeAzDashboardFetchGrafanaAvailablePlugin_FetchViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/InvokeAzDashboardFetchGrafanaAvailablePlugin_FetchViaIdentity.cs new file mode 100644 index 00000000000..e27dd67c358 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/InvokeAzDashboardFetchGrafanaAvailablePlugin_FetchViaIdentity.cs @@ -0,0 +1,514 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// A synchronous resource action. + /// + /// [OpenAPI] FetchAvailablePlugins=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/fetchAvailablePlugins" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzDashboardFetchGrafanaAvailablePlugin_FetchViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IGrafanaAvailablePluginListResponse))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"A synchronous resource action.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/fetchAvailablePlugins", ApiVersion = "2024-11-01-preview")] + public partial class InvokeAzDashboardFetchGrafanaAvailablePlugin_FetchViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IGrafanaAvailablePluginListResponse + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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 InvokeAzDashboardFetchGrafanaAvailablePlugin_FetchViaIdentity() + { + + } + + /// 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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaFetchAvailablePlugins' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.GrafanaFetchAvailablePluginsViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.GrafanaFetchAvailablePlugins(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IGrafanaAvailablePluginListResponse + /// 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.Dashboard.Models.IGrafanaAvailablePluginListResponse + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / 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.Dashboard.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaFetchAvailablePlugins_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateExpanded.cs new file mode 100644 index 00000000000..c2070f3f564 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateExpanded.cs @@ -0,0 +1,916 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// create a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or create an + /// existing grafana. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardGrafana_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or create an existing grafana.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + public partial class NewAzDashboardGrafana_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The grafana resource type. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana(); + + /// The api key setting of the Grafana instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The api key setting of the Grafana instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string ApiKey { get => _requestBodyParametersBody.ApiKey ?? null; set => _requestBodyParametersBody.ApiKey = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Scope for dns deterministic name hash calculation. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Scope for dns deterministic name hash calculation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Scope for dns deterministic name hash calculation.", + SerializedName = @"autoGeneratedDomainNameLabelScope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("TenantReuse")] + public string AutoGeneratedDomainNameLabelScope { get => _requestBodyParametersBody.AutoGeneratedDomainNameLabelScope ?? null; set => _requestBodyParametersBody.AutoGeneratedDomainNameLabelScope = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether a Grafana instance uses deterministic outbound IPs.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string DeterministicOutboundIP { get => _requestBodyParametersBody.DeterministicOutboundIP ?? null; set => _requestBodyParametersBody.DeterministicOutboundIP = 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 => _requestBodyParametersBody.IdentityType = value.IsPresent ? "SystemAssigned": null ; } + + /// The AutoRenew setting of the Enterprise subscription + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The AutoRenew setting of the Enterprise subscription")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => _requestBodyParametersBody.EnterpriseConfigurationMarketplaceAutoRenew ?? null; set => _requestBodyParametersBody.EnterpriseConfigurationMarketplaceAutoRenew = value; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Plan Id of the Azure Marketplace subscription for the Enterprise plugins")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + public string EnterpriseConfigurationMarketplacePlanId { get => _requestBodyParametersBody.EnterpriseConfigurationMarketplacePlanId ?? null; set => _requestBodyParametersBody.EnterpriseConfigurationMarketplacePlanId = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Array of AzureMonitorWorkspaceIntegration + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Array of AzureMonitorWorkspaceIntegration")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration[] GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => _requestBodyParametersBody.GrafanaIntegrationAzureMonitorWorkspaceIntegration?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.GrafanaIntegrationAzureMonitorWorkspaceIntegration = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The major Grafana software version to target. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The major Grafana software version to target.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + public string GrafanaMajorVersion { get => _requestBodyParametersBody.GrafanaMajorVersion ?? null; set => _requestBodyParametersBody.GrafanaMajorVersion = value; } + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get => _requestBodyParametersBody.GrafanaPlugin ?? null /* object */; set => _requestBodyParametersBody.GrafanaPlugin = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _requestBodyParametersBody.Location ?? null; set => _requestBodyParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Indicate the state for enable or disable traffic over the public interface. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Indicate the state for enable or disable traffic over the public interface.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + public string PublicNetworkAccess { get => _requestBodyParametersBody.PublicNetworkAccess ?? null; set => _requestBodyParametersBody.PublicNetworkAccess = 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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true to execute the CSRF check even if the login cookie is not in a request (default false).")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SecurityCsrfAlwaysCheck { get => _requestBodyParametersBody.SecurityCsrfAlwaysCheck ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SecurityCsrfAlwaysCheck = value; } + + /// The name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string SkuName { get => _requestBodyParametersBody.SkuName ?? null; set => _requestBodyParametersBody.SkuName = value; } + + /// Enable this to allow Grafana to send email. Default is false + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Enable this to allow Grafana to send email. Default is false")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SmtpEnabled { get => _requestBodyParametersBody.SmtpEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SmtpEnabled = value; } + + /// Address used when sending out emailshttps://pkg.go.dev/net/mail#Address + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Address used when sending out emailshttps://pkg.go.dev/net/mail#Address")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Address used when sending out emailshttps://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + public string SmtpFromAddress { get => _requestBodyParametersBody.SmtpFromAddress ?? null; set => _requestBodyParametersBody.SmtpFromAddress = value; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification"https://pkg.go.dev/net/mail#Address + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name to be used when sending out emails. Default is \"Azure Managed Grafana Notification\"https://pkg.go.dev/net/mail#Address")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification""https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + public string SmtpFromName { get => _requestBodyParametersBody.SmtpFromName ?? null; set => _requestBodyParametersBody.SmtpFromName = value; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "SMTP server hostname with port, e.g. test.email.net:587")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + public string SmtpHost { get => _requestBodyParametersBody.SmtpHost ?? null; set => _requestBodyParametersBody.SmtpHost = value; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + public System.Security.SecureString SmtpPassword { get => _requestBodyParametersBody.SmtpPassword ?? null; set => _requestBodyParametersBody.SmtpPassword = value; } + + /// + /// Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SmtpSkipVerify { get => _requestBodyParametersBody.SmtpSkipVerify ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SmtpSkipVerify = value; } + + /// + /// The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + public string SmtpStartTlsPolicy { get => _requestBodyParametersBody.SmtpStartTlsPolicy ?? null; set => _requestBodyParametersBody.SmtpStartTlsPolicy = value; } + + /// User of SMTP auth + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User of SMTP auth")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + public string SmtpUser { get => _requestBodyParametersBody.SmtpUser ?? null; set => _requestBodyParametersBody.SmtpUser = value; } + + /// Set to false to disable external snapshot publish endpoint + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to false to disable external snapshot publish endpoint")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SnapshotExternalEnabled { get => _requestBodyParametersBody.SnapshotExternalEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SnapshotExternalEnabled = 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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to false to disable capture screenshot in Unified Alert due to performance issue.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UnifiedAlertingScreenshotCaptureEnabled { get => _requestBodyParametersBody.UnifiedAlertingScreenshotCaptureEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UnifiedAlertingScreenshotCaptureEnabled = 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; } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true so editors can administrate dashboards, folders and teams they create.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UserEditorsCanAdmin { get => _requestBodyParametersBody.UserEditorsCanAdmin ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UserEditorsCanAdmin = value; } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UserViewersCanEdit { get => _requestBodyParametersBody.UserViewersCanEdit ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UserViewersCanEdit = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// The zone redundancy setting of the Grafana instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The zone redundancy setting of the Grafana instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string ZoneRedundancy { get => _requestBodyParametersBody.ZoneRedundancy ?? null; set => _requestBodyParametersBody.ZoneRedundancy = 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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardGrafana_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardGrafana_CreateExpanded Clone() + { + var clone = new NewAzDashboardGrafana_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.WorkspaceName = this.WorkspaceName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardGrafana_CreateExpanded() + { + + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _requestBodyParametersBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _requestBodyParametersBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_requestBodyParametersBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _requestBodyParametersBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _requestBodyParametersBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.GrafanaCreate(SubscriptionId, ResourceGroupName, WorkspaceName, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..1accc52031e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateViaJsonFilePath.cs @@ -0,0 +1,576 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// create a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or create an + /// existing grafana. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardGrafana_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or create an existing grafana.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardGrafana_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + public global::System.String _jsonString; + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardGrafana_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardGrafana_CreateViaJsonFilePath Clone() + { + var clone = new NewAzDashboardGrafana_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.WorkspaceName = this.WorkspaceName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardGrafana_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaCreateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateViaJsonString.cs new file mode 100644 index 00000000000..17109feebd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardGrafana_CreateViaJsonString.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// create a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or create an + /// existing grafana. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardGrafana_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or create an existing grafana.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardGrafana_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardGrafana_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardGrafana_CreateViaJsonString Clone() + { + var clone = new NewAzDashboardGrafana_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.WorkspaceName = this.WorkspaceName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardGrafana_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaCreateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateExpanded.cs new file mode 100644 index 00000000000..5251bcf8fce --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateExpanded.cs @@ -0,0 +1,638 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// create a IntegrationFabric + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardIntegrationFabric_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class NewAzDashboardIntegrationFabric_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The integration fabric resource type. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabric(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// + /// The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, + /// an Azure Data Explorer cluster, etc. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, an Azure Data Explorer cluster, etc.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource Id of the Azure resource which is used to configure Grafana data source. E.g., an Azure Monitor Workspace, an Azure Data Explorer cluster, etc.", + SerializedName = @"dataSourceResourceId", + PossibleTypes = new [] { typeof(string) })] + public string DataSourceResourceId { get => _requestBodyParametersBody.DataSourceResourceId ?? null; set => _requestBodyParametersBody.DataSourceResourceId = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _requestBodyParametersBody.Location ?? null; set => _requestBodyParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// A list of integration scenarios covered by this integration fabric + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A list of integration scenarios covered by this integration fabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of integration scenarios covered by this integration fabric", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + public string[] Scenario { get => _requestBodyParametersBody.Scenario?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.Scenario = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// + /// The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource Id of the Azure resource being integrated with Azure Managed Grafana. E.g., an Azure Kubernetes Service cluster.", + SerializedName = @"targetResourceId", + PossibleTypes = new [] { typeof(string) })] + public string TargetResourceId { get => _requestBodyParametersBody.TargetResourceId ?? null; set => _requestBodyParametersBody.TargetResourceId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardIntegrationFabric_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardIntegrationFabric_CreateExpanded Clone() + { + var clone = new NewAzDashboardIntegrationFabric_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardIntegrationFabric_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsCreate(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..0c67750bc92 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateViaJsonFilePath.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// create a IntegrationFabric + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardIntegrationFabric_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardIntegrationFabric_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + public global::System.String _jsonString; + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardIntegrationFabric_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardIntegrationFabric_CreateViaJsonFilePath Clone() + { + var clone = new NewAzDashboardIntegrationFabric_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardIntegrationFabric_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsCreateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateViaJsonString.cs new file mode 100644 index 00000000000..5653be843f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardIntegrationFabric_CreateViaJsonString.cs @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// create a IntegrationFabric + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardIntegrationFabric_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardIntegrationFabric_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardIntegrationFabric_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardIntegrationFabric_CreateViaJsonString Clone() + { + var clone = new NewAzDashboardIntegrationFabric_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardIntegrationFabric_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsCreateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateExpanded.cs new file mode 100644 index 00000000000..8c83eba9353 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateExpanded.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardManagedDashboard_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an existing dashboard.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class NewAzDashboardManagedDashboard_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The managed dashboard resource type. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboard(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _requestBodyParametersBody.Location ?? null; set => _requestBodyParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardManagedDashboard_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardManagedDashboard_CreateExpanded Clone() + { + var clone = new NewAzDashboardManagedDashboard_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.DashboardName = this.DashboardName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardManagedDashboard_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsCreate(SubscriptionId, ResourceGroupName, DashboardName, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..9d7df9f778b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateViaJsonFilePath.cs @@ -0,0 +1,576 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardManagedDashboard_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an existing dashboard.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardManagedDashboard_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + public global::System.String _jsonString; + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardManagedDashboard_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardManagedDashboard_CreateViaJsonFilePath Clone() + { + var clone = new NewAzDashboardManagedDashboard_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.DashboardName = this.DashboardName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardManagedDashboard_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsCreateViaJsonString(SubscriptionId, ResourceGroupName, DashboardName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateViaJsonString.cs new file mode 100644 index 00000000000..4707e0d36f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedDashboard_CreateViaJsonString.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an + /// existing dashboard. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardManagedDashboard_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard or create an existing dashboard.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardManagedDashboard_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardManagedDashboard_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardManagedDashboard_CreateViaJsonString Clone() + { + var clone = new NewAzDashboardManagedDashboard_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.DashboardName = this.DashboardName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardManagedDashboard_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsCreateViaJsonString(SubscriptionId, ResourceGroupName, DashboardName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateExpanded.cs new file mode 100644 index 00000000000..d69a686c8ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateExpanded.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// create a managed private endpoint for a grafana resource. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardManagedPrivateEndpoint_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a managed private endpoint for a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class NewAzDashboardManagedPrivateEndpoint_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The managed private endpoint resource type. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointModel(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// The group Ids of the managed private endpoint. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The group Ids of the managed private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The group Ids of the managed private endpoint.", + SerializedName = @"groupIds", + PossibleTypes = new [] { typeof(string) })] + public string[] GroupId { get => _requestBodyParametersBody.GroupId?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.GroupId = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _requestBodyParametersBody.Location ?? null; set => _requestBodyParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// The ARM resource ID of the resource for which the managed private endpoint is pointing to. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ARM resource ID of the resource for which the managed private endpoint is pointing to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM resource ID of the resource for which the managed private endpoint is pointing to.", + SerializedName = @"privateLinkResourceId", + PossibleTypes = new [] { typeof(string) })] + public string PrivateLinkResourceId { get => _requestBodyParametersBody.PrivateLinkResourceId ?? null; set => _requestBodyParametersBody.PrivateLinkResourceId = value; } + + /// + /// The region of the resource to which the managed private endpoint is pointing to. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The region of the resource to which the managed private endpoint is pointing to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The region of the resource to which the managed private endpoint is pointing to.", + SerializedName = @"privateLinkResourceRegion", + PossibleTypes = new [] { typeof(string) })] + public string PrivateLinkResourceRegion { get => _requestBodyParametersBody.PrivateLinkResourceRegion ?? null; set => _requestBodyParametersBody.PrivateLinkResourceRegion = value; } + + /// + /// The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration + /// page without the protocol and port. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration page without the protocol and port.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL of the data store behind the private link service. It would be the URL in the Grafana data source configuration page without the protocol and port.", + SerializedName = @"privateLinkServiceUrl", + PossibleTypes = new [] { typeof(string) })] + public string PrivateLinkServiceUrl { get => _requestBodyParametersBody.PrivateLinkServiceUrl ?? null; set => _requestBodyParametersBody.PrivateLinkServiceUrl = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// User input request message of the managed private endpoint. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User input request message of the managed private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User input request message of the managed private endpoint.", + SerializedName = @"requestMessage", + PossibleTypes = new [] { typeof(string) })] + public string RequestMessage { get => _requestBodyParametersBody.RequestMessage ?? null; set => _requestBodyParametersBody.RequestMessage = 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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ITrackedResourceTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzDashboardManagedPrivateEndpoint_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardManagedPrivateEndpoint_CreateExpanded Clone() + { + var clone = new NewAzDashboardManagedPrivateEndpoint_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardManagedPrivateEndpoint_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsCreate(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..91c0950dfe4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath.cs @@ -0,0 +1,591 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// create a managed private endpoint for a grafana resource. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a managed private endpoint for a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + public global::System.String _jsonString; + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath Clone() + { + var clone = new NewAzDashboardManagedPrivateEndpoint_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardManagedPrivateEndpoint_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsCreateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString.cs new file mode 100644 index 00000000000..99ce78802d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// create a managed private endpoint for a grafana resource. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzDashboardManagedPrivateEndpoint_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"create a managed private endpoint for a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString Clone() + { + var clone = new NewAzDashboardManagedPrivateEndpoint_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 NewAzDashboardManagedPrivateEndpoint_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsCreateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardGrafana_Delete.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardGrafana_Delete.cs new file mode 100644 index 00000000000..09d595b4e19 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardGrafana_Delete.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a workspace for Grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardGrafana_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a workspace for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardGrafana_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzDashboardGrafana_Delete + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardGrafana_Delete Clone() + { + var clone = new RemoveAzDashboardGrafana_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.WorkspaceName = this.WorkspaceName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaDelete(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardGrafana_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardGrafana_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardGrafana_DeleteViaIdentity.cs new file mode 100644 index 00000000000..281a44b0976 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardGrafana_DeleteViaIdentity.cs @@ -0,0 +1,572 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a workspace for Grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardGrafana_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a workspace for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardGrafana_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzDashboardGrafana_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardGrafana_DeleteViaIdentity Clone() + { + var clone = new RemoveAzDashboardGrafana_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.GrafanaDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.GrafanaDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardGrafana_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_Delete.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_Delete.cs new file mode 100644 index 00000000000..c7b2fcdd279 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_Delete.cs @@ -0,0 +1,610 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a IntegrationFabric + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardIntegrationFabric_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardIntegrationFabric_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzDashboardIntegrationFabric_Delete + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardIntegrationFabric_Delete Clone() + { + var clone = new RemoveAzDashboardIntegrationFabric_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsDelete(SubscriptionId, ResourceGroupName, WorkspaceName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardIntegrationFabric_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_DeleteViaIdentity.cs new file mode 100644 index 00000000000..15c1badb9a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_DeleteViaIdentity.cs @@ -0,0 +1,576 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a IntegrationFabric + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardIntegrationFabric_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardIntegrationFabric_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzDashboardIntegrationFabric_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardIntegrationFabric_DeleteViaIdentity Clone() + { + var clone = new RemoveAzDashboardIntegrationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IntegrationFabricsDeleteViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.IntegrationFabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.IntegrationFabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IntegrationFabricsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, InputObject.IntegrationFabricName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardIntegrationFabric_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana.cs new file mode 100644 index 00000000000..12d49be7d59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana.cs @@ -0,0 +1,591 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a IntegrationFabric + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardIntegrationFabric_DeleteViaIdentityGrafana", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _grafanaInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity GrafanaInputObject { get => this._grafanaInputObject; set => this._grafanaInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana Clone() + { + var clone = new RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (GrafanaInputObject?.Id != null) + { + this.GrafanaInputObject.Id += $"/integrationFabrics/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.IntegrationFabricsDeleteViaIdentity(GrafanaInputObject.Id, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == GrafanaInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + await this.Client.IntegrationFabricsDelete(GrafanaInputObject.SubscriptionId ?? null, GrafanaInputObject.ResourceGroupName ?? null, GrafanaInputObject.WorkspaceName ?? null, Name, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardIntegrationFabric_DeleteViaIdentityGrafana() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedDashboard_Delete.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedDashboard_Delete.cs new file mode 100644 index 00000000000..065a2955308 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedDashboard_Delete.cs @@ -0,0 +1,526 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a dashboard for Grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardManagedDashboard_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a dashboard for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardManagedDashboard_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsDelete(SubscriptionId, ResourceGroupName, DashboardName, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardManagedDashboard_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedDashboard_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedDashboard_DeleteViaIdentity.cs new file mode 100644 index 00000000000..b61ece256d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedDashboard_DeleteViaIdentity.cs @@ -0,0 +1,507 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a dashboard for Grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardManagedDashboard_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a dashboard for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardManagedDashboard_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ManagedDashboardsDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.DashboardName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DashboardName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ManagedDashboardsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.DashboardName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardManagedDashboard_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_Delete.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_Delete.cs new file mode 100644 index 00000000000..af018add6b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_Delete.cs @@ -0,0 +1,610 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a managed private endpoint for a grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardManagedPrivateEndpoint_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a managed private endpoint for a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardManagedPrivateEndpoint_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzDashboardManagedPrivateEndpoint_Delete + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardManagedPrivateEndpoint_Delete Clone() + { + var clone = new RemoveAzDashboardManagedPrivateEndpoint_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsDelete(SubscriptionId, ResourceGroupName, WorkspaceName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardManagedPrivateEndpoint_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity.cs new file mode 100644 index 00000000000..916c9bf5645 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity.cs @@ -0,0 +1,578 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a managed private endpoint for a grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardManagedPrivateEndpoint_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a managed private endpoint for a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity Clone() + { + var clone = new RemoveAzDashboardManagedPrivateEndpoint_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ManagedPrivateEndpointsDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ManagedPrivateEndpointName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ManagedPrivateEndpointName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ManagedPrivateEndpointsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, InputObject.ManagedPrivateEndpointName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana.cs new file mode 100644 index 00000000000..1e0f1f2010d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Delete a managed private endpoint for a grafana resource. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Delete a managed private endpoint for a grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _grafanaInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity GrafanaInputObject { get => this._grafanaInputObject; set => this._grafanaInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana Clone() + { + var clone = new RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (GrafanaInputObject?.Id != null) + { + this.GrafanaInputObject.Id += $"/managedPrivateEndpoints/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ManagedPrivateEndpointsDeleteViaIdentity(GrafanaInputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == GrafanaInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + await this.Client.ManagedPrivateEndpointsDelete(GrafanaInputObject.SubscriptionId ?? null, GrafanaInputObject.ResourceGroupName ?? null, GrafanaInputObject.WorkspaceName ?? null, Name, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzDashboardManagedPrivateEndpoint_DeleteViaIdentityGrafana() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/TestAzDashboardGrafanaEnterpriseDetail_Check.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/TestAzDashboardGrafanaEnterpriseDetail_Check.cs new file mode 100644 index 00000000000..3eb8e03d81d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/TestAzDashboardGrafanaEnterpriseDetail_Check.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Retrieve enterprise add-on details information + /// + /// [OpenAPI] CheckEnterpriseDetails=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/checkEnterpriseDetails" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzDashboardGrafanaEnterpriseDetail_Check", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Retrieve enterprise add-on details information")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/checkEnterpriseDetails", ApiVersion = "2024-11-01-preview")] + public partial class TestAzDashboardGrafanaEnterpriseDetail_Check : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IEnterpriseDetails + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCheckEnterpriseDetails' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GrafanaCheckEnterpriseDetails(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzDashboardGrafanaEnterpriseDetail_Check() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IEnterpriseDetails + /// 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.Dashboard.Models.IEnterpriseDetails + 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/Dashboard.Management.brown/target/generated/cmdlets/TestAzDashboardGrafanaEnterpriseDetail_CheckViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/TestAzDashboardGrafanaEnterpriseDetail_CheckViaIdentity.cs new file mode 100644 index 00000000000..bd87b665510 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/TestAzDashboardGrafanaEnterpriseDetail_CheckViaIdentity.cs @@ -0,0 +1,486 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// Retrieve enterprise add-on details information + /// + /// [OpenAPI] CheckEnterpriseDetails=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/checkEnterpriseDetails" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzDashboardGrafanaEnterpriseDetail_CheckViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IEnterpriseDetails))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Retrieve enterprise add-on details information")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/checkEnterpriseDetails", ApiVersion = "2024-11-01-preview")] + public partial class TestAzDashboardGrafanaEnterpriseDetail_CheckViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IEnterpriseDetails + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCheckEnterpriseDetails' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.GrafanaCheckEnterpriseDetailsViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.GrafanaCheckEnterpriseDetails(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzDashboardGrafanaEnterpriseDetail_CheckViaIdentity() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IEnterpriseDetails + /// 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.Dashboard.Models.IEnterpriseDetails + 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/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardGrafana_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardGrafana_UpdateExpanded.cs new file mode 100644 index 00000000000..6757598a4c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardGrafana_UpdateExpanded.cs @@ -0,0 +1,1008 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardGrafana_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an existing grafana.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + public partial class UpdateAzDashboardGrafana_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The grafana resource type. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana(); + + /// The api key setting of the Grafana instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The api key setting of the Grafana instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string ApiKey { get => _requestBodyParametersBody.ApiKey ?? null; set => _requestBodyParametersBody.ApiKey = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether a Grafana instance uses deterministic outbound IPs.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string DeterministicOutboundIP { get => _requestBodyParametersBody.DeterministicOutboundIP ?? null; set => _requestBodyParametersBody.DeterministicOutboundIP = 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; } + + /// The AutoRenew setting of the Enterprise subscription + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The AutoRenew setting of the Enterprise subscription")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => _requestBodyParametersBody.EnterpriseConfigurationMarketplaceAutoRenew ?? null; set => _requestBodyParametersBody.EnterpriseConfigurationMarketplaceAutoRenew = value; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Plan Id of the Azure Marketplace subscription for the Enterprise plugins")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + public string EnterpriseConfigurationMarketplacePlanId { get => _requestBodyParametersBody.EnterpriseConfigurationMarketplacePlanId ?? null; set => _requestBodyParametersBody.EnterpriseConfigurationMarketplacePlanId = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Array of AzureMonitorWorkspaceIntegration + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Array of AzureMonitorWorkspaceIntegration")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration[] GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => _requestBodyParametersBody.GrafanaIntegrationAzureMonitorWorkspaceIntegration?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.GrafanaIntegrationAzureMonitorWorkspaceIntegration = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The major Grafana software version to target. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The major Grafana software version to target.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + public string GrafanaMajorVersion { get => _requestBodyParametersBody.GrafanaMajorVersion ?? null; set => _requestBodyParametersBody.GrafanaMajorVersion = value; } + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get => _requestBodyParametersBody.GrafanaPlugin ?? null /* object */; set => _requestBodyParametersBody.GrafanaPlugin = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Indicate the state for enable or disable traffic over the public interface. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Indicate the state for enable or disable traffic over the public interface.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + public string PublicNetworkAccess { get => _requestBodyParametersBody.PublicNetworkAccess ?? null; set => _requestBodyParametersBody.PublicNetworkAccess = 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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true to execute the CSRF check even if the login cookie is not in a request (default false).")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SecurityCsrfAlwaysCheck { get => _requestBodyParametersBody.SecurityCsrfAlwaysCheck ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SecurityCsrfAlwaysCheck = value; } + + /// The name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string SkuName { get => _requestBodyParametersBody.SkuName ?? null; set => _requestBodyParametersBody.SkuName = value; } + + /// Enable this to allow Grafana to send email. Default is false + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Enable this to allow Grafana to send email. Default is false")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SmtpEnabled { get => _requestBodyParametersBody.SmtpEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SmtpEnabled = value; } + + /// Address used when sending out emailshttps://pkg.go.dev/net/mail#Address + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Address used when sending out emailshttps://pkg.go.dev/net/mail#Address")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Address used when sending out emailshttps://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + public string SmtpFromAddress { get => _requestBodyParametersBody.SmtpFromAddress ?? null; set => _requestBodyParametersBody.SmtpFromAddress = value; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification"https://pkg.go.dev/net/mail#Address + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name to be used when sending out emails. Default is \"Azure Managed Grafana Notification\"https://pkg.go.dev/net/mail#Address")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification""https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + public string SmtpFromName { get => _requestBodyParametersBody.SmtpFromName ?? null; set => _requestBodyParametersBody.SmtpFromName = value; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "SMTP server hostname with port, e.g. test.email.net:587")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + public string SmtpHost { get => _requestBodyParametersBody.SmtpHost ?? null; set => _requestBodyParametersBody.SmtpHost = value; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + public System.Security.SecureString SmtpPassword { get => _requestBodyParametersBody.SmtpPassword ?? null; set => _requestBodyParametersBody.SmtpPassword = value; } + + /// + /// Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SmtpSkipVerify { get => _requestBodyParametersBody.SmtpSkipVerify ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SmtpSkipVerify = value; } + + /// + /// The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + public string SmtpStartTlsPolicy { get => _requestBodyParametersBody.SmtpStartTlsPolicy ?? null; set => _requestBodyParametersBody.SmtpStartTlsPolicy = value; } + + /// User of SMTP auth + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User of SMTP auth")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + public string SmtpUser { get => _requestBodyParametersBody.SmtpUser ?? null; set => _requestBodyParametersBody.SmtpUser = value; } + + /// Set to false to disable external snapshot publish endpoint + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to false to disable external snapshot publish endpoint")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SnapshotExternalEnabled { get => _requestBodyParametersBody.SnapshotExternalEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SnapshotExternalEnabled = 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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to false to disable capture screenshot in Unified Alert due to performance issue.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UnifiedAlertingScreenshotCaptureEnabled { get => _requestBodyParametersBody.UnifiedAlertingScreenshotCaptureEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UnifiedAlertingScreenshotCaptureEnabled = 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; } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true so editors can administrate dashboards, folders and teams they create.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UserEditorsCanAdmin { get => _requestBodyParametersBody.UserEditorsCanAdmin ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UserEditorsCanAdmin = value; } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UserViewersCanEdit { get => _requestBodyParametersBody.UserViewersCanEdit ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UserViewersCanEdit = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// The zone redundancy setting of the Grafana instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The zone redundancy setting of the Grafana instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string ZoneRedundancy { get => _requestBodyParametersBody.ZoneRedundancy ?? null; set => _requestBodyParametersBody.ZoneRedundancy = 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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzDashboardGrafana_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardGrafana_UpdateExpanded Clone() + { + var clone = new UpdateAzDashboardGrafana_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.WorkspaceName = this.WorkspaceName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 == _requestBodyParametersBody?.IdentityType?.Contains("SystemAssigned")); + bool supportsUserAssignedIdentity = false; + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _requestBodyParametersBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _requestBodyParametersBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UserAssignedIdentity()); + } + } + supportsUserAssignedIdentity = true == this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && this.UserAssignedIdentity?.Length > 0 || + true != this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && true == _requestBodyParametersBody.IdentityType?.Contains("UserAssigned"); + if (!supportsUserAssignedIdentity) + { + _requestBodyParametersBody.IdentityUserAssignedIdentity = null; + } + // calculate IdentityType + if ((supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _requestBodyParametersBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else if ((supportsUserAssignedIdentity && !supportsSystemAssignedIdentity)) + { + _requestBodyParametersBody.IdentityType = "UserAssigned"; + } + else if ((!supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _requestBodyParametersBody.IdentityType = "SystemAssigned"; + } + else + { + _requestBodyParametersBody.IdentityType = "None"; + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _requestBodyParametersBody = await this.Client.GrafanaGetWithResult(SubscriptionId, ResourceGroupName, WorkspaceName, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_requestBodyParametersBody(); + await this.Client.GrafanaCreate(SubscriptionId, ResourceGroupName, WorkspaceName, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardGrafana_UpdateExpanded() + { + + } + + private void Update_requestBodyParametersBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ZoneRedundancy"))) + { + this.ZoneRedundancy = (string)(this.MyInvocation?.BoundParameters["ZoneRedundancy"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ApiKey"))) + { + this.ApiKey = (string)(this.MyInvocation?.BoundParameters["ApiKey"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PublicNetworkAccess"))) + { + this.PublicNetworkAccess = (string)(this.MyInvocation?.BoundParameters["PublicNetworkAccess"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DeterministicOutboundIP"))) + { + this.DeterministicOutboundIP = (string)(this.MyInvocation?.BoundParameters["DeterministicOutboundIP"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("GrafanaPlugin"))) + { + this.GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins)(this.MyInvocation?.BoundParameters["GrafanaPlugin"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("GrafanaMajorVersion"))) + { + this.GrafanaMajorVersion = (string)(this.MyInvocation?.BoundParameters["GrafanaMajorVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SkuName"))) + { + this.SkuName = (string)(this.MyInvocation?.BoundParameters["SkuName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("GrafanaIntegrationAzureMonitorWorkspaceIntegration"))) + { + this.GrafanaIntegrationAzureMonitorWorkspaceIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration[])(this.MyInvocation?.BoundParameters["GrafanaIntegrationAzureMonitorWorkspaceIntegration"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("EnterpriseConfigurationMarketplacePlanId"))) + { + this.EnterpriseConfigurationMarketplacePlanId = (string)(this.MyInvocation?.BoundParameters["EnterpriseConfigurationMarketplacePlanId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("EnterpriseConfigurationMarketplaceAutoRenew"))) + { + this.EnterpriseConfigurationMarketplaceAutoRenew = (string)(this.MyInvocation?.BoundParameters["EnterpriseConfigurationMarketplaceAutoRenew"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpEnabled"))) + { + this.SmtpEnabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SmtpEnabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpHost"))) + { + this.SmtpHost = (string)(this.MyInvocation?.BoundParameters["SmtpHost"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpUser"))) + { + this.SmtpUser = (string)(this.MyInvocation?.BoundParameters["SmtpUser"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpPassword"))) + { + this.SmtpPassword = (System.Security.SecureString)(this.MyInvocation?.BoundParameters["SmtpPassword"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpFromAddress"))) + { + this.SmtpFromAddress = (string)(this.MyInvocation?.BoundParameters["SmtpFromAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpFromName"))) + { + this.SmtpFromName = (string)(this.MyInvocation?.BoundParameters["SmtpFromName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpStartTlsPolicy"))) + { + this.SmtpStartTlsPolicy = (string)(this.MyInvocation?.BoundParameters["SmtpStartTlsPolicy"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpSkipVerify"))) + { + this.SmtpSkipVerify = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SmtpSkipVerify"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SnapshotExternalEnabled"))) + { + this.SnapshotExternalEnabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SnapshotExternalEnabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserViewersCanEdit"))) + { + this.UserViewersCanEdit = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["UserViewersCanEdit"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserEditorsCanAdmin"))) + { + this.UserEditorsCanAdmin = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["UserEditorsCanAdmin"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SecurityCsrfAlwaysCheck"))) + { + this.SecurityCsrfAlwaysCheck = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SecurityCsrfAlwaysCheck"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UnifiedAlertingScreenshotCaptureEnabled"))) + { + this.UnifiedAlertingScreenshotCaptureEnabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["UnifiedAlertingScreenshotCaptureEnabled"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardGrafana_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardGrafana_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..66da9e824a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardGrafana_UpdateViaIdentityExpanded.cs @@ -0,0 +1,989 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an + /// existing grafana. + /// + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardGrafana_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a workspace for Grafana resource. This API is idempotent, so user can either update a new grafana or update an existing grafana.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + public partial class UpdateAzDashboardGrafana_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The grafana resource type. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafana _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedGrafana(); + + /// The api key setting of the Grafana instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The api key setting of the Grafana instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The api key setting of the Grafana instance.", + SerializedName = @"apiKey", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string ApiKey { get => _requestBodyParametersBody.ApiKey ?? null; set => _requestBodyParametersBody.ApiKey = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Whether a Grafana instance uses deterministic outbound IPs. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether a Grafana instance uses deterministic outbound IPs.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether a Grafana instance uses deterministic outbound IPs.", + SerializedName = @"deterministicOutboundIP", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string DeterministicOutboundIP { get => _requestBodyParametersBody.DeterministicOutboundIP ?? null; set => _requestBodyParametersBody.DeterministicOutboundIP = 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; } + + /// The AutoRenew setting of the Enterprise subscription + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The AutoRenew setting of the Enterprise subscription")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The AutoRenew setting of the Enterprise subscription", + SerializedName = @"marketplaceAutoRenew", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string EnterpriseConfigurationMarketplaceAutoRenew { get => _requestBodyParametersBody.EnterpriseConfigurationMarketplaceAutoRenew ?? null; set => _requestBodyParametersBody.EnterpriseConfigurationMarketplaceAutoRenew = value; } + + /// The Plan Id of the Azure Marketplace subscription for the Enterprise plugins + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Plan Id of the Azure Marketplace subscription for the Enterprise plugins")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Plan Id of the Azure Marketplace subscription for the Enterprise plugins", + SerializedName = @"marketplacePlanId", + PossibleTypes = new [] { typeof(string) })] + public string EnterpriseConfigurationMarketplacePlanId { get => _requestBodyParametersBody.EnterpriseConfigurationMarketplacePlanId ?? null; set => _requestBodyParametersBody.EnterpriseConfigurationMarketplacePlanId = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Array of AzureMonitorWorkspaceIntegration + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Array of AzureMonitorWorkspaceIntegration")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Array of AzureMonitorWorkspaceIntegration", + SerializedName = @"azureMonitorWorkspaceIntegrations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration[] GrafanaIntegrationAzureMonitorWorkspaceIntegration { get => _requestBodyParametersBody.GrafanaIntegrationAzureMonitorWorkspaceIntegration?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.GrafanaIntegrationAzureMonitorWorkspaceIntegration = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The major Grafana software version to target. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The major Grafana software version to target.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The major Grafana software version to target.", + SerializedName = @"grafanaMajorVersion", + PossibleTypes = new [] { typeof(string) })] + public string GrafanaMajorVersion { get => _requestBodyParametersBody.GrafanaMajorVersion ?? null; set => _requestBodyParametersBody.GrafanaMajorVersion = value; } + + /// + /// Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Installed plugin list of the Grafana instance. Key is plugin id, value is plugin definition.", + SerializedName = @"grafanaPlugins", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins GrafanaPlugin { get => _requestBodyParametersBody.GrafanaPlugin ?? null /* object */; set => _requestBodyParametersBody.GrafanaPlugin = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Indicate the state for enable or disable traffic over the public interface. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Indicate the state for enable or disable traffic over the public interface.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Indicate the state for enable or disable traffic over the public interface.", + SerializedName = @"publicNetworkAccess", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Enabled", "Disabled")] + public string PublicNetworkAccess { get => _requestBodyParametersBody.PublicNetworkAccess ?? null; set => _requestBodyParametersBody.PublicNetworkAccess = value; } + + /// + /// Set to true to execute the CSRF check even if the login cookie is not in a request (default false). + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true to execute the CSRF check even if the login cookie is not in a request (default false).")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true to execute the CSRF check even if the login cookie is not in a request (default false).", + SerializedName = @"csrfAlwaysCheck", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SecurityCsrfAlwaysCheck { get => _requestBodyParametersBody.SecurityCsrfAlwaysCheck ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SecurityCsrfAlwaysCheck = value; } + + /// The name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string SkuName { get => _requestBodyParametersBody.SkuName ?? null; set => _requestBodyParametersBody.SkuName = value; } + + /// Enable this to allow Grafana to send email. Default is false + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Enable this to allow Grafana to send email. Default is false")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Enable this to allow Grafana to send email. Default is false", + SerializedName = @"enabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SmtpEnabled { get => _requestBodyParametersBody.SmtpEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SmtpEnabled = value; } + + /// Address used when sending out emailshttps://pkg.go.dev/net/mail#Address + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Address used when sending out emailshttps://pkg.go.dev/net/mail#Address")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Address used when sending out emailshttps://pkg.go.dev/net/mail#Address", + SerializedName = @"fromAddress", + PossibleTypes = new [] { typeof(string) })] + public string SmtpFromAddress { get => _requestBodyParametersBody.SmtpFromAddress ?? null; set => _requestBodyParametersBody.SmtpFromAddress = value; } + + /// + /// Name to be used when sending out emails. Default is "Azure Managed Grafana Notification"https://pkg.go.dev/net/mail#Address + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name to be used when sending out emails. Default is \"Azure Managed Grafana Notification\"https://pkg.go.dev/net/mail#Address")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name to be used when sending out emails. Default is ""Azure Managed Grafana Notification""https://pkg.go.dev/net/mail#Address", + SerializedName = @"fromName", + PossibleTypes = new [] { typeof(string) })] + public string SmtpFromName { get => _requestBodyParametersBody.SmtpFromName ?? null; set => _requestBodyParametersBody.SmtpFromName = value; } + + /// SMTP server hostname with port, e.g. test.email.net:587 + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "SMTP server hostname with port, e.g. test.email.net:587")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"SMTP server hostname with port, e.g. test.email.net:587", + SerializedName = @"host", + PossibleTypes = new [] { typeof(string) })] + public string SmtpHost { get => _requestBodyParametersBody.SmtpHost ?? null; set => _requestBodyParametersBody.SmtpHost = value; } + + /// + /// Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Password of SMTP auth. If the password contains # or ;, then you have to wrap it with triple quotes", + SerializedName = @"password", + PossibleTypes = new [] { typeof(System.Security.SecureString) })] + public System.Security.SecureString SmtpPassword { get => _requestBodyParametersBody.SmtpPassword ?? null; set => _requestBodyParametersBody.SmtpPassword = value; } + + /// + /// Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Verify SSL for SMTP server. Default is falsehttps://pkg.go.dev/crypto/tls#Config", + SerializedName = @"skipVerify", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SmtpSkipVerify { get => _requestBodyParametersBody.SmtpSkipVerify ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SmtpSkipVerify = value; } + + /// + /// The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The StartTLSPolicy setting of the SMTP configurationhttps://pkg.go.dev/github.com/go-mail/mail#StartTLSPolicy", + SerializedName = @"startTLSPolicy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("OpportunisticStartTLS", "MandatoryStartTLS", "NoStartTLS")] + public string SmtpStartTlsPolicy { get => _requestBodyParametersBody.SmtpStartTlsPolicy ?? null; set => _requestBodyParametersBody.SmtpStartTlsPolicy = value; } + + /// User of SMTP auth + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User of SMTP auth")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User of SMTP auth", + SerializedName = @"user", + PossibleTypes = new [] { typeof(string) })] + public string SmtpUser { get => _requestBodyParametersBody.SmtpUser ?? null; set => _requestBodyParametersBody.SmtpUser = value; } + + /// Set to false to disable external snapshot publish endpoint + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to false to disable external snapshot publish endpoint")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to false to disable external snapshot publish endpoint", + SerializedName = @"externalEnabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SnapshotExternalEnabled { get => _requestBodyParametersBody.SnapshotExternalEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.SnapshotExternalEnabled = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// + /// Set to false to disable capture screenshot in Unified Alert due to performance issue. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to false to disable capture screenshot in Unified Alert due to performance issue.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to false to disable capture screenshot in Unified Alert due to performance issue.", + SerializedName = @"captureEnabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UnifiedAlertingScreenshotCaptureEnabled { get => _requestBodyParametersBody.UnifiedAlertingScreenshotCaptureEnabled ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UnifiedAlertingScreenshotCaptureEnabled = 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; } + + /// + /// Set to true so editors can administrate dashboards, folders and teams they create. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true so editors can administrate dashboards, folders and teams they create.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true so editors can administrate dashboards, folders and teams they create.", + SerializedName = @"editorsCanAdmin", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UserEditorsCanAdmin { get => _requestBodyParametersBody.UserEditorsCanAdmin ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UserEditorsCanAdmin = value; } + + /// + /// Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access + /// to. They cannot save their changes. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Set to true so viewers can access and use explore and perform temporary edits on panels in dashboards they have access to. They cannot save their changes.", + SerializedName = @"viewersCanEdit", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter UserViewersCanEdit { get => _requestBodyParametersBody.UserViewersCanEdit ?? default(global::System.Management.Automation.SwitchParameter); set => _requestBodyParametersBody.UserViewersCanEdit = value; } + + /// The zone redundancy setting of the Grafana instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The zone redundancy setting of the Grafana instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The zone redundancy setting of the Grafana instance.", + SerializedName = @"zoneRedundancy", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.PSArgumentCompleterAttribute("Disabled", "Enabled")] + public string ZoneRedundancy { get => _requestBodyParametersBody.ZoneRedundancy ?? null; set => _requestBodyParametersBody.ZoneRedundancy = 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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzDashboardGrafana_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardGrafana_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzDashboardGrafana_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._requestBodyParametersBody = this._requestBodyParametersBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 == _requestBodyParametersBody?.IdentityType?.Contains("SystemAssigned")); + bool supportsUserAssignedIdentity = false; + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _requestBodyParametersBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _requestBodyParametersBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.UserAssignedIdentity()); + } + } + supportsUserAssignedIdentity = true == this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && this.UserAssignedIdentity?.Length > 0 || + true != this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && true == _requestBodyParametersBody.IdentityType?.Contains("UserAssigned"); + if (!supportsUserAssignedIdentity) + { + _requestBodyParametersBody.IdentityUserAssignedIdentity = null; + } + // calculate IdentityType + if ((supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _requestBodyParametersBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else if ((supportsUserAssignedIdentity && !supportsSystemAssignedIdentity)) + { + _requestBodyParametersBody.IdentityType = "UserAssigned"; + } + else if ((!supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _requestBodyParametersBody.IdentityType = "SystemAssigned"; + } + else + { + _requestBodyParametersBody.IdentityType = "None"; + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GrafanaCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _requestBodyParametersBody = await this.Client.GrafanaGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_requestBodyParametersBody(); + await this.Client.GrafanaCreateViaIdentity(InputObject.Id, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _requestBodyParametersBody = await this.Client.GrafanaGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_requestBodyParametersBody(); + await this.Client.GrafanaCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardGrafana_UpdateViaIdentityExpanded() + { + + } + + private void Update_requestBodyParametersBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ZoneRedundancy"))) + { + this.ZoneRedundancy = (string)(this.MyInvocation?.BoundParameters["ZoneRedundancy"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ApiKey"))) + { + this.ApiKey = (string)(this.MyInvocation?.BoundParameters["ApiKey"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PublicNetworkAccess"))) + { + this.PublicNetworkAccess = (string)(this.MyInvocation?.BoundParameters["PublicNetworkAccess"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DeterministicOutboundIP"))) + { + this.DeterministicOutboundIP = (string)(this.MyInvocation?.BoundParameters["DeterministicOutboundIP"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("GrafanaPlugin"))) + { + this.GrafanaPlugin = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedGrafanaPropertiesGrafanaPlugins)(this.MyInvocation?.BoundParameters["GrafanaPlugin"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("GrafanaMajorVersion"))) + { + this.GrafanaMajorVersion = (string)(this.MyInvocation?.BoundParameters["GrafanaMajorVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SkuName"))) + { + this.SkuName = (string)(this.MyInvocation?.BoundParameters["SkuName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("GrafanaIntegrationAzureMonitorWorkspaceIntegration"))) + { + this.GrafanaIntegrationAzureMonitorWorkspaceIntegration = (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IAzureMonitorWorkspaceIntegration[])(this.MyInvocation?.BoundParameters["GrafanaIntegrationAzureMonitorWorkspaceIntegration"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("EnterpriseConfigurationMarketplacePlanId"))) + { + this.EnterpriseConfigurationMarketplacePlanId = (string)(this.MyInvocation?.BoundParameters["EnterpriseConfigurationMarketplacePlanId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("EnterpriseConfigurationMarketplaceAutoRenew"))) + { + this.EnterpriseConfigurationMarketplaceAutoRenew = (string)(this.MyInvocation?.BoundParameters["EnterpriseConfigurationMarketplaceAutoRenew"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpEnabled"))) + { + this.SmtpEnabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SmtpEnabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpHost"))) + { + this.SmtpHost = (string)(this.MyInvocation?.BoundParameters["SmtpHost"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpUser"))) + { + this.SmtpUser = (string)(this.MyInvocation?.BoundParameters["SmtpUser"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpPassword"))) + { + this.SmtpPassword = (System.Security.SecureString)(this.MyInvocation?.BoundParameters["SmtpPassword"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpFromAddress"))) + { + this.SmtpFromAddress = (string)(this.MyInvocation?.BoundParameters["SmtpFromAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpFromName"))) + { + this.SmtpFromName = (string)(this.MyInvocation?.BoundParameters["SmtpFromName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpStartTlsPolicy"))) + { + this.SmtpStartTlsPolicy = (string)(this.MyInvocation?.BoundParameters["SmtpStartTlsPolicy"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SmtpSkipVerify"))) + { + this.SmtpSkipVerify = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SmtpSkipVerify"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SnapshotExternalEnabled"))) + { + this.SnapshotExternalEnabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SnapshotExternalEnabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserViewersCanEdit"))) + { + this.UserViewersCanEdit = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["UserViewersCanEdit"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserEditorsCanAdmin"))) + { + this.UserEditorsCanAdmin = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["UserEditorsCanAdmin"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SecurityCsrfAlwaysCheck"))) + { + this.SecurityCsrfAlwaysCheck = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SecurityCsrfAlwaysCheck"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UnifiedAlertingScreenshotCaptureEnabled"))) + { + this.UnifiedAlertingScreenshotCaptureEnabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["UnifiedAlertingScreenshotCaptureEnabled"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedGrafana + /// 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.Dashboard.Models.IManagedGrafana + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateExpanded.cs new file mode 100644 index 00000000000..16693268938 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateExpanded.cs @@ -0,0 +1,600 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a IntegrationFabric + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardIntegrationFabric_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardIntegrationFabric_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The parameters for a PATCH request to a Integration Fabric resource. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParameters(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The new integration scenarios covered by this integration fabric. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new integration scenarios covered by this integration fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new integration scenarios covered by this integration fabric.", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + public string[] Scenario { get => _requestBodyParametersBody.Scenario?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.Scenario = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// The new tags of the Integration Fabric resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the Integration Fabric resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the Integration Fabric resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzDashboardIntegrationFabric_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardIntegrationFabric_UpdateExpanded Clone() + { + var clone = new UpdateAzDashboardIntegrationFabric_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsUpdate(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardIntegrationFabric_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..6a660d4e926 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a IntegrationFabric + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardIntegrationFabric_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The parameters for a PATCH request to a Integration Fabric resource. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParameters(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The new integration scenarios covered by this integration fabric. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new integration scenarios covered by this integration fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new integration scenarios covered by this integration fabric.", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + public string[] Scenario { get => _requestBodyParametersBody.Scenario?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.Scenario = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The new tags of the Integration Fabric resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the Integration Fabric resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the Integration Fabric resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzDashboardIntegrationFabric_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._requestBodyParametersBody = this._requestBodyParametersBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IntegrationFabricsUpdateViaIdentity(InputObject.Id, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.IntegrationFabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.IntegrationFabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IntegrationFabricsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, InputObject.IntegrationFabricName ?? null, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardIntegrationFabric_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded.cs new file mode 100644 index 00000000000..3851102c3e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded.cs @@ -0,0 +1,582 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a IntegrationFabric + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The parameters for a PATCH request to a Integration Fabric resource. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IntegrationFabricUpdateParameters(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _grafanaInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity GrafanaInputObject { get => this._grafanaInputObject; set => this._grafanaInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The new integration scenarios covered by this integration fabric. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new integration scenarios covered by this integration fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new integration scenarios covered by this integration fabric.", + SerializedName = @"scenarios", + PossibleTypes = new [] { typeof(string) })] + public string[] Scenario { get => _requestBodyParametersBody.Scenario?.ToArray() ?? null /* fixedArrayOf */; set => _requestBodyParametersBody.Scenario = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The new tags of the Integration Fabric resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the Integration Fabric resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the Integration Fabric resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabricUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded Clone() + { + var clone = new UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded(); + 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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (GrafanaInputObject?.Id != null) + { + this.GrafanaInputObject.Id += $"/integrationFabrics/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.IntegrationFabricsUpdateViaIdentity(GrafanaInputObject.Id, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == GrafanaInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + await this.Client.IntegrationFabricsUpdate(GrafanaInputObject.SubscriptionId ?? null, GrafanaInputObject.ResourceGroupName ?? null, GrafanaInputObject.WorkspaceName ?? null, Name, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzDashboardIntegrationFabric_UpdateViaIdentityGrafanaExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..2dcfa0cfa91 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath.cs @@ -0,0 +1,591 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a IntegrationFabric + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardIntegrationFabric_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + public global::System.String _jsonString; + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzDashboardIntegrationFabric_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsUpdateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardIntegrationFabric_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaJsonString.cs new file mode 100644 index 00000000000..63bd0a7cee3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardIntegrationFabric_UpdateViaJsonString.cs @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a IntegrationFabric + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardIntegrationFabric_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IIntegrationFabric))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a IntegrationFabric")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/integrationFabrics/{integrationFabricName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class UpdateAzDashboardIntegrationFabric_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The integration fabric name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The integration fabric name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The integration fabric name of Azure Managed Grafana.", + SerializedName = @"integrationFabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("IntegrationFabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzDashboardIntegrationFabric_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardIntegrationFabric_UpdateViaJsonString Clone() + { + var clone = new UpdateAzDashboardIntegrationFabric_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IntegrationFabricsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IntegrationFabricsUpdateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardIntegrationFabric_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IIntegrationFabric + /// 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.Dashboard.Models.IIntegrationFabric + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateExpanded.cs new file mode 100644 index 00000000000..b4a9ed11643 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateExpanded.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a dashboard for Grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedDashboard_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a dashboard for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedDashboard_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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; + + /// The parameters for a PATCH request to a managed dashboard resource. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardUpdateParameters(); + + /// + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// The new tags of the managed dashboard resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the managed dashboard resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the managed dashboard resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsUpdate(SubscriptionId, ResourceGroupName, DashboardName, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedDashboard_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + 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/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..48d087fbe58 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaIdentityExpanded.cs @@ -0,0 +1,501 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a dashboard for Grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedDashboard_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a dashboard for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedDashboard_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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; + + /// The parameters for a PATCH request to a managed dashboard resource. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedDashboardUpdateParameters(); + + /// + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The new tags of the managed dashboard resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the managed dashboard resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the managed dashboard resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboardUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ManagedDashboardsUpdateViaIdentity(InputObject.Id, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.DashboardName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DashboardName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ManagedDashboardsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.DashboardName ?? null, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedDashboard_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + 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/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..973918c99ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaJsonFilePath.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a dashboard for Grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedDashboard_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a dashboard for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class UpdateAzDashboardManagedDashboard_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsUpdateViaJsonString(SubscriptionId, ResourceGroupName, DashboardName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedDashboard_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + 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/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaJsonString.cs new file mode 100644 index 00000000000..e4cfdfb9708 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedDashboard_UpdateViaJsonString.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a dashboard for Grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedDashboard_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedDashboard))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a dashboard for Grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class UpdateAzDashboardManagedDashboard_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _dashboardName; + + /// The name of the Azure Managed Dashboard. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Managed Dashboard.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure Managed Dashboard.", + SerializedName = @"dashboardName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string DashboardName { get => this._dashboardName; set => this._dashboardName = 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedDashboardsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedDashboardsUpdateViaJsonString(SubscriptionId, ResourceGroupName, DashboardName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,DashboardName=DashboardName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedDashboard_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedDashboard + /// 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.Dashboard.Models.IManagedDashboard + 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/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_Refresh.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_Refresh.cs new file mode 100644 index 00000000000..04eaec5f7a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_Refresh.cs @@ -0,0 +1,562 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// Refresh and sync managed private endpoints of a grafana resource to latest state. + /// + /// + /// [OpenAPI] Refresh=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/refreshManagedPrivateEndpoints" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_Refresh", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Refresh and sync managed private endpoints of a grafana resource to latest state.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/refreshManagedPrivateEndpoints", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedPrivateEndpoint_Refresh : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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. + /// /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_Refresh + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_Refresh Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_Refresh(); + 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.WorkspaceName = this.WorkspaceName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsRefresh' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsRefresh(SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_Refresh() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity.cs new file mode 100644 index 00000000000..2d0b2f55c38 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity.cs @@ -0,0 +1,542 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// + /// Refresh and sync managed private endpoints of a grafana resource to latest state. + /// + /// + /// [OpenAPI] Refresh=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/refreshManagedPrivateEndpoints" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_RefreshViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"Refresh and sync managed private endpoints of a grafana resource to latest state.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/refreshManagedPrivateEndpoints", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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. + /// /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity(); + 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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsRefresh' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ManagedPrivateEndpointsRefreshViaIdentity(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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ManagedPrivateEndpointsRefresh(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_RefreshViaIdentity() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded.cs new file mode 100644 index 00000000000..ff75ba02995 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded.cs @@ -0,0 +1,588 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a managed private endpoint for an existing grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a managed private endpoint for an existing grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The parameters for a PATCH request to a managed private endpoint. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParameters(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// The new tags of the managed private endpoint. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the managed private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the managed private endpoint.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.Tag = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsUpdate(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..a1dae9394f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded.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.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a managed private endpoint for an existing grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a managed private endpoint for an existing grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The parameters for a PATCH request to a managed private endpoint. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParameters(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity 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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The new tags of the managed private endpoint. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the managed private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the managed private endpoint.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_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._requestBodyParametersBody = this._requestBodyParametersBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ManagedPrivateEndpointsUpdateViaIdentity(InputObject.Id, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ManagedPrivateEndpointName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ManagedPrivateEndpointName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ManagedPrivateEndpointsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.WorkspaceName ?? null, InputObject.ManagedPrivateEndpointName ?? null, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded.cs new file mode 100644 index 00000000000..64ecec68db9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded.cs @@ -0,0 +1,570 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a managed private endpoint for an existing grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a managed private endpoint for an existing grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + public partial class UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// The parameters for a PATCH request to a managed private endpoint. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParameters _requestBodyParametersBody = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.ManagedPrivateEndpointUpdateParameters(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity _grafanaInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IDashboardIdentity GrafanaInputObject { get => this._grafanaInputObject; set => this._grafanaInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The new tags of the managed private endpoint. + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The new tags of the managed private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The new tags of the managed private endpoint.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointUpdateParametersTags Tag { get => _requestBodyParametersBody.Tag ?? null /* object */; set => _requestBodyParametersBody.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded(); + 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._requestBodyParametersBody = this._requestBodyParametersBody; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (GrafanaInputObject?.Id != null) + { + this.GrafanaInputObject.Id += $"/managedPrivateEndpoints/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ManagedPrivateEndpointsUpdateViaIdentity(GrafanaInputObject.Id, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == GrafanaInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + if (null == GrafanaInputObject.WorkspaceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("GrafanaInputObject has null value for GrafanaInputObject.WorkspaceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, GrafanaInputObject) ); + } + await this.Client.ManagedPrivateEndpointsUpdate(GrafanaInputObject.SubscriptionId ?? null, GrafanaInputObject.ResourceGroupName ?? null, GrafanaInputObject.WorkspaceName ?? null, Name, _requestBodyParametersBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_UpdateViaIdentityGrafanaExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..dbe21421ddf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a managed private endpoint for an existing grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a managed private endpoint for an existing grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + public global::System.String _jsonString; + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsUpdateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString.cs new file mode 100644 index 00000000000..dfed73907be --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/cmdlets/UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Cmdlets; + using System; + + /// update a managed private endpoint for an existing grafana resource. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzDashboardManagedPrivateEndpoint_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Models.IManagedPrivateEndpointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Description(@"update a managed private endpoint for an existing grafana resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName}/managedPrivateEndpoints/{managedPrivateEndpointName}", ApiVersion = "2024-11-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.NotSuggestDefaultParameterSet] + public partial class UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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(); + + /// 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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.MicrosoftDashboard Client => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The managed private endpoint name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The managed private endpoint name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The managed private endpoint name of Azure Managed Grafana.", + SerializedName = @"managedPrivateEndpointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ManagedPrivateEndpointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The workspace name of Azure Managed Grafana. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The workspace name of Azure Managed Grafana.")] + [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The workspace name of Azure Managed Grafana.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Dashboard.ParameterCategory.Path)] + 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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Cmdlets.UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString Clone() + { + var clone = new UpdateAzDashboardManagedPrivateEndpoint_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.WorkspaceName = this.WorkspaceName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ManagedPrivateEndpointsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ManagedPrivateEndpointsUpdateViaJsonString(SubscriptionId, ResourceGroupName, WorkspaceName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzDashboardManagedPrivateEndpoint_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.Models.IManagedPrivateEndpointModel + /// 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.Dashboard.Models.IManagedPrivateEndpointModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..4cbf8a1eb5b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..9a7b1f02299 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..9bed5d52f50 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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/Dashboard.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..a43ce214280 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard +{ + 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/Dashboard.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..2db98a8a1c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard +{ + 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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..86ce5d87263 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..3d673ffee70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..9f8e1f01bd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..3b29a131009 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..13c6161ea70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..ffa31e7e143 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..f52bccdb2b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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: Dashboard 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.Dashboard.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.Dashboard.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 Dashboard".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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..9589090f28c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..2198e8c8f1d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..185e327e2ac --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..4d958e08ed9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..73f8c6717c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..fb326c7f496 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..47f293e9536 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..7d3e81fb0ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..e1282dfdbfe --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,211 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.Dashboard.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 static string CapitalizeFirstLetter(string text) + { + if (string.IsNullOrEmpty(text)) + return text; + + return char.ToUpper(text[0]) + text.Substring(1); + } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = CapitalizeFirstLetter(helpObject.GetProperty("Synopsis")); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + Description = CapitalizeFirstLetter(Description); + 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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..afa44d080df --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..f21051eec54 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,681 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.Dashboard.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetLoginVerification() + { + if (!VariantGroup.IsInternal && IsAzure && !VariantGroup.IsModelCmdlet) + { + return $@" +{Indent}{Indent}$context = Get-AzContext +{Indent}{Indent}if (-not $context -and -not $testPlayback) {{ +{Indent}{Indent}{Indent}Write-Error ""No Azure login detected. Please run 'Connect-AzAccount' to log in."" +{Indent}{Indent}{Indent}exit +{Indent}{Indent}}} +"; + } + return ""; + } + + 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.Dashboard.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 +{Indent}{Indent} +{Indent}{Indent}$testPlayback = $false +{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }} +{GetLoginVerification()}{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}if ($wrappedCmd -eq $null) {{ +{Indent}{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Function) +{Indent}{Indent}}} +{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}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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..02757e33ec5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,549 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.Dashboard.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 bool IsModelCmdlet { 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; + IsModelCmdlet = Variants.All(v => v.IsModelCmdlet); + 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 IsModelCmdlet { 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(); + IsModelCmdlet = 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(); + Description = PsHelpInfo.CapitalizeFirstLetter(Description); + // 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/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..ddbb50daadd --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,136 @@ +/*--------------------------------------------------------------------------------------------- + * 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.Dashboard +{ + [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 | AttributeTargets.Property)] + public class ModelCmdletAttribute : 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/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..66f888f6a77 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..1c7578b8392 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..22664392ad1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..c0e10db4afb --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..c418f6b9a1a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..8f18d96dd8d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParameters, 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.Dashboard.MicrosoftDashboard Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..8d590684181 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..e97970e2cf1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..c21e4dcd901 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..b44d64bf052 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..617434993ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..4a6512de8ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..ac77dc729fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..35a5ea4a5ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..5c7ec7793fc --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..a7b4f18f63e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..d50eb6bbb3e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..bea874f0214 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..0c432d6908b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..49729a76d32 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..212aec9156c --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..c66ebc18d1b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..ce31aeacdab --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..f9670d6d1ac --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..ff16123a7d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..b62bf45e591 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..fa1e7744455 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..2b7c2fc9578 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..23a0f1e6a67 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..8d34a2cb1d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..04c80dcc906 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..a3e85c65a92 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..68c8c54098f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..4f3854fc28b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..aa1db632b90 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..c341285ee2a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..b9cc0692fe1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..0e0d6b39e9e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..b19f5da1ce9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..11f37348782 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..bd75d951f75 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..ed5cbcb84e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..ff1cfb9f588 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..d5b4ceba3d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..4c331c28288 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..d2ace41077e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..036025d6948 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..8d7d9181868 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..738fca112d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..d9faaca75bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..ff09351c4e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..2c499da4c97 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..480b9a73c54 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..ab283ca6421 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..51a07627c6b --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..aa05841e979 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..ff19f9ca386 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..3d8b6e07ca4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..32ea11e8ca5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..83bb619c381 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..9427ad5a6ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..1208a32b0d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..8a8ef6d91ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..ee8a718bca1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,353 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Dashboard.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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 description of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //Name of the module that is being deprecated + public string moduleName { get; set; } = String.IsNullOrEmpty(@"") ? @"Az.Dashboard" : @""; + + //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.moduleName, 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/Dashboard.Management.brown/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..ecfac6fe848 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..ea21d4dfcec --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..7a8d7dccfd3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..1d6922a23a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..1a08da361d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..3015e0666dd --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..09a729a202f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..d96f9e16372 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..eefb67dd422 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..419cb028bb9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..5ee7cc86734 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..971045e1805 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..5f157223834 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..d5f508bafee --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..b9e74230736 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..4815eaa03f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..701b19bc8b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..d6ec54ae5df --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..76146311931 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..c86454de5d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..5debecd33f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..157f7526b8a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..fc84018870a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..689a031f538 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..18bb60f7aef --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..9b2cf2c9cf0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..72fbd1b82c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..4ef90b70573 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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 in '{0}' from version : '{1}' + + + ```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/Dashboard.Management.brown/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..55bb6507264 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..32e8ded0137 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..fba9b6be90f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..3d60a60cbb2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..044ad35c4a6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..9d781dbfd62 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..85236265a87 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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.Dashboard.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..ce435b3fe77 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..81d0412d8d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/how-to.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/how-to.md new file mode 100644 index 00000000000..9acc7dfb0e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.Dashboard`. + +## Building `Az.Dashboard` +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.Dashboard` +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.Dashboard` +To pack `Az.Dashboard` 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.Dashboard`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Dashboard.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Dashboard.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Dashboard`. + - `-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.Dashboard` 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/Dashboard.Management.brown/target/internal/Az.Dashboard.internal.psm1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/internal/Az.Dashboard.internal.psm1 new file mode 100644 index 00000000000..851c142b78e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/internal/Az.Dashboard.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Dashboard.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Dashboard.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/Dashboard.Management.brown/target/internal/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/internal/README.md new file mode 100644 index 00000000000..1628a6e27f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.Dashboard`. Instead, this sub-module is imported by the `..\custom\Az.Dashboard.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.Dashboard.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.Dashboard`. diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/license.txt b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/pack-module.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/resources/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/run-module.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/run-module.ps1 new file mode 100644 index 00000000000..66733b2b146 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/test-module.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/test-module.ps1 new file mode 100644 index 00000000000..5a19a56748f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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.Dashboard.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/Dashboard.Management.brown/target/test/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/README.md new file mode 100644 index 00000000000..d28996846ef --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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: + - https://github.com/Azure/azure-rest-api-specs/blob/d55f30f41f04e712de101fc9c17a591ca410bfed/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/Dashboard.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/Dashboard.Management.brown/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/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/Dashboard.Management.brown/tspconfig.yaml b/tests-upgrade/tests-emitter/Dashboard.Management.brown/tspconfig.yaml new file mode 100644 index 00000000000..bb50a1cf529 --- /dev/null +++ b/tests-upgrade/tests-emitter/Dashboard.Management.brown/tspconfig.yaml @@ -0,0 +1,84 @@ +parameters: + "service-dir": + default: "sdk/dashboard" +emit: + - "@azure-tools/typespec-autorest" +options: + "@azure-tools/typespec-autorest": + omit-unreachable-types: true + emitter-output-dir: "{project-root}/.." + azure-resource-provider-folder: "resource-manager" + output-file: "{azure-resource-provider-folder}/{service-name}/{version-status}/{version}/grafana.json" + examples-dir: "{project-root}/examples" + "@azure-tools/typespec-csharp": + flavor: azure + package-dir: "Azure.ResourceManager.Grafana" + clear-output-folder: true + model-namespace: true + namespace: "{package-dir}" + service-dir: "sdk/grafana" + "@azure-tools/typespec-python": + package-dir: "azure-mgmt-dashboard" + namespace: "azure.mgmt.dashboard" + generate-test: true + generate-sample: true + flavor: "azure" + "@azure-tools/typespec-java": + package-dir: "azure-resourcemanager-dashboard" + namespace: "com.azure.resourcemanager.dashboard" + service-name: "Dashboard" # human-readable service name, whitespace allowed + flavor: azure + "@azure-tools/typespec-ts": + service-dir: sdk/dashboard + package-dir: "arm-dashboard" + is-modular-library: true + flavor: "azure" + experimental-extensible-enums: true + package-details: + name: "@azure/arm-dashboard" + "@azure-tools/typespec-go": + service-dir: "sdk/resourcemanager/dashboard" + package-dir: "armdashboard" + module: "github.com/Azure/azure-sdk-for-go/{service-dir}/{package-dir}" + fix-const-stuttering: true + flavor: "azure" + generate-samples: true + generate-fakes: true + head-as-boolean: true + inject-spans: true + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "Dashboard/Dashboard.Autorest" + clear-output-folder: true + azure: true + module-version: 0.1.0 + prefix: 'Az' + subject-prefix: 'Dashboard' + service-name: Dashboard + module-name: "{prefix}.{service-name}" + emit-modeler-output: true + # 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' + # Following are common directives which are normally required in all the RPs + # 1. Remove the unexpanded parameter set + # 2. For New-* cmdlets, ViaIdentity is not required + - where: + variant: ^(Create|Update)(?!.*?Expanded|ViaJsonString|ViaJsonFilePath) + remove: true + - where: + variant: ^CreateViaIdentity.*$ + remove: true +linter: + extends: + - "@azure-tools/typespec-azure-rulesets/resource-manager" diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/EmailConfigurationModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/EmailConfigurationModel.tsp new file mode 100644 index 00000000000..64d25c7011b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/EmailConfigurationModel.tsp @@ -0,0 +1,56 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Email configuration model. + */ +@parentResource(VaultModel) +model EmailConfigurationModel + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = EmailConfigurationModel, + KeyName = "emailConfigurationName", + SegmentName = "alertSettings", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(EmailConfiguration.create::parameters.resource, + "x-ms-client-name", + "body" +); + +#suppress "@azure-tools/typespec-azure-resource-manager/no-resource-delete-operation" "This resource does not need a delete operation defined" +@armResourceOperations +interface EmailConfiguration { + /** + * Gets the details of the alert configuration setting. + */ + get is ArmResourceRead; + + /** + * Creates an alert configuration setting for the given vault. + */ + create is ArmResourceCreateOrReplaceSync; + + /** + * Gets the list of alert configuration settings for the given vault. + */ + list is ArmResourceListByParent; +} + +@@doc(EmailConfigurationModel.name, "The email configuration name."); +@@doc(EmailConfiguration.create::parameters.resource, + "EmailConfiguration model." +); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/EventModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/EventModel.tsp new file mode 100644 index 00000000000..25acee13be4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/EventModel.tsp @@ -0,0 +1,63 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Event model. + */ +@parentResource(VaultModel) +model EventModel is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = EventModel, + KeyName = "eventName", + SegmentName = "events", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +@armResourceOperations +interface Event { + /** + * Gets the details of the event. + */ + get is ArmResourceRead; + + /** + * Gets the list of events in the given vault. + */ + list is ArmResourceListByParent< + EventModel, + { + ...Azure.ResourceManager.Foundations.BaseParameters; + + /** + * OData options. + */ + @query("odataOptions") + odataOptions?: string; + + /** + * Continuation token. + */ + @query("continuationToken") + continuationToken?: string; + + /** + * Page size. + */ + @query("pageSize") + pageSize?: int32; + } + >; +} + +@@doc(EventModel.name, "The event name."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/FabricAgentModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/FabricAgentModel.tsp new file mode 100644 index 00000000000..7a4e73b0c1c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/FabricAgentModel.tsp @@ -0,0 +1,58 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./FabricModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Fabric agent model. + */ +@parentResource(FabricModel) +model FabricAgentModel + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = FabricAgentModel, + KeyName = "fabricAgentName", + SegmentName = "fabricAgents", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(FabricAgent.create::parameters.resource, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface FabricAgent { + /** + * Gets the details of the fabric agent. + */ + get is ArmResourceRead; + + /** + * Creates the fabric agent. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Deletes fabric agent. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the list of fabric agents in the given fabric. + */ + list is ArmResourceListByParent; +} + +@@doc(FabricAgentModel.name, "The fabric agent name."); +@@doc(FabricAgent.create::parameters.resource, "Fabric agent model."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/FabricModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/FabricModel.tsp new file mode 100644 index 00000000000..a9f3f9f748a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/FabricModel.tsp @@ -0,0 +1,83 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Fabric model. + */ +model FabricModel + is Azure.ResourceManager.TrackedResource { + ...ResourceNameParameter< + Resource = FabricModel, + KeyName = "fabricName", + SegmentName = "replicationFabrics", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(Fabric.create::parameters.resource, + "x-ms-client-name", + "body" +); +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(Fabric.update::parameters.properties, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface Fabric { + /** + * Gets the details of the fabric. + */ + get is ArmResourceRead; + + /** + * Creates the fabric. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Performs update on the fabric. + */ + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchAsync; + + /** + * Removes the fabric. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the list of fabrics in the given subscription and resource group. + */ + list is ArmResourceListByParent< + FabricModel, + { + ...Azure.ResourceManager.Foundations.BaseParameters; + + /** + * Continuation token from the previous call. + */ + @query("continuationToken") + continuationToken?: string; + } + >; + + /** + * Gets the list of fabrics in the given subscription. + */ + listBySubscription is ArmListBySubscription; +} + +@@doc(FabricModel.name, "The fabric name."); +@@doc(Fabric.create::parameters.resource, "Fabric properties."); +@@doc(Fabric.update::parameters.properties, "Fabric properties."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/JobModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/JobModel.tsp new file mode 100644 index 00000000000..4b08e2ef686 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/JobModel.tsp @@ -0,0 +1,63 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Job model. + */ +@parentResource(VaultModel) +model JobModel is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = JobModel, + KeyName = "jobName", + SegmentName = "jobs", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +@armResourceOperations +interface Job { + /** + * Gets the details of the job. + */ + get is ArmResourceRead; + + /** + * Gets the list of jobs in the given vault. + */ + list is ArmResourceListByParent< + JobModel, + { + ...Azure.ResourceManager.Foundations.BaseParameters; + + /** + * OData options. + */ + @query("odataOptions") + odataOptions?: string; + + /** + * Continuation token. + */ + @query("continuationToken") + continuationToken?: string; + + /** + * Page size. + */ + @query("pageSize") + pageSize?: int32; + } + >; +} + +@@doc(JobModel.name, "The job name."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/PolicyModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PolicyModel.tsp new file mode 100644 index 00000000000..bdaa340114b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PolicyModel.tsp @@ -0,0 +1,58 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Policy model. + */ +@parentResource(VaultModel) +model PolicyModel + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PolicyModel, + KeyName = "policyName", + SegmentName = "replicationPolicies", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(Policy.create::parameters.resource, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface Policy { + /** + * Gets the details of the policy. + */ + get is ArmResourceRead; + + /** + * Creates the policy. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Removes the policy. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the list of policies in the given vault. + */ + list is ArmResourceListByParent; +} + +@@doc(PolicyModel.name, "The policy name."); +@@doc(Policy.create::parameters.resource, "Policy model."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateEndpointConnection.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateEndpointConnection.tsp new file mode 100644 index 00000000000..59b184613eb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateEndpointConnection.tsp @@ -0,0 +1,59 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Represents private endpoint connection. + */ +@parentResource(VaultModel) +model PrivateEndpointConnection + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PrivateEndpointConnection, + KeyName = "privateEndpointConnectionName", + SegmentName = "privateEndpointConnections", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(PrivateEndpointConnections.update::parameters.resource, + "x-ms-client-name", + "body" +); +@armResourceOperations +interface PrivateEndpointConnections { + /** + * Gets the private endpoint connection details. + */ + get is ArmResourceRead; + + /** + * Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + */ + update is ArmResourceCreateOrReplaceSync; + + /** + * Deletes the private endpoint connection. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the all private endpoint connections configured on the vault. + */ + list is ArmResourceListByParent; +} + +@@doc(PrivateEndpointConnection.name, "The private endpoint connection name."); +@@doc(PrivateEndpointConnections.update::parameters.resource, + "Private endpoint connection update input." +); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateEndpointConnectionProxy.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateEndpointConnectionProxy.tsp new file mode 100644 index 00000000000..711421342d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateEndpointConnectionProxy.tsp @@ -0,0 +1,80 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Represents private endpoint connection proxy request. + */ +@parentResource(VaultModel) +model PrivateEndpointConnectionProxy + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PrivateEndpointConnectionProxy, + KeyName = "privateEndpointConnectionProxyName", + SegmentName = "privateEndpointConnectionProxies", + NamePattern = "^[a-zA-Z0-9-.]*$" + >; + + /** + * Gets or sets ETag. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" + etag?: string; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(PrivateEndpointConnectionProxies.create::parameters.resource, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface PrivateEndpointConnectionProxies { + /** + * Gets the private endpoint connection proxy details. + */ + get is ArmResourceRead; + + /** + * Create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also create a private endpoint connection resource. + */ + create is ArmResourceCreateOrReplaceSync; + + /** + * Returns the operation to track the deletion of private endpoint connection proxy. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the all private endpoint connections proxies. + */ + list is ArmResourceListByParent; + + /** + * Returns remote private endpoint connection information after validation. + */ + validate is ArmResourceActionSync< + PrivateEndpointConnectionProxy, + PrivateEndpointConnectionProxy, + PrivateEndpointConnectionProxy + >; +} + +@@doc(PrivateEndpointConnectionProxy.name, + "The private endpoint connection proxy name." +); +@@doc(PrivateEndpointConnectionProxies.create::parameters.resource, + "Private endpoint connection creation input." +); +@@doc(PrivateEndpointConnectionProxies.validate::parameters.body, + "The private endpoint connection proxy input." +); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateLinkResource.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateLinkResource.tsp new file mode 100644 index 00000000000..90d757d4e5d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/PrivateLinkResource.tsp @@ -0,0 +1,41 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Represents private link resource. + */ +@parentResource(VaultModel) +model PrivateLinkResource + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = PrivateLinkResource, + KeyName = "privateLinkResourceName", + SegmentName = "privateLinkResources", + NamePattern = "^[a-zA-Z0-9-.]*$" + >; +} + +@armResourceOperations +interface PrivateLinkResources { + /** + * Gets the details of site recovery private link resource. + */ + get is ArmResourceRead; + + /** + * Gets the list of private link resources. + */ + list is ArmResourceListByParent; +} + +@@doc(PrivateLinkResource.name, "The private link name."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/ProtectedItemModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/ProtectedItemModel.tsp new file mode 100644 index 00000000000..045743982d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/ProtectedItemModel.tsp @@ -0,0 +1,116 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Protected item model. + */ +@parentResource(VaultModel) +model ProtectedItemModel + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = ProtectedItemModel, + KeyName = "protectedItemName", + SegmentName = "protectedItems", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(ProtectedItem.create::parameters.resource, + "x-ms-client-name", + "body" +); +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(ProtectedItem.update::parameters.properties, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface ProtectedItem { + /** + * Gets the details of the protected item. + */ + get is ArmResourceRead; + + /** + * Creates the protected item. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Performs update on the protected item. + */ + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchAsync; + + /** + * Removes the protected item. + */ + delete is ArmResourceDeleteWithoutOkAsync< + ProtectedItemModel, + { + ...Azure.ResourceManager.Foundations.BaseParameters; + + /** + * A flag indicating whether to do force delete or not. + */ + @query("forceDelete") + forceDelete?: boolean; + } + >; + + /** + * Gets the list of protected items in the given vault. + */ + list is ArmResourceListByParent< + ProtectedItemModel, + { + ...Azure.ResourceManager.Foundations.BaseParameters; + + /** + * OData options. + */ + @query("odataOptions") + odataOptions?: string; + + /** + * Continuation token. + */ + @query("continuationToken") + continuationToken?: string; + + /** + * Page size. + */ + @query("pageSize") + pageSize?: int32; + } + >; + + /** + * Performs the planned failover on the protected item. + */ + plannedFailover is ArmResourceActionAsync< + ProtectedItemModel, + PlannedFailoverModel, + PlannedFailoverModel + >; +} + +@@doc(ProtectedItemModel.name, "The protected item name."); +@@doc(ProtectedItem.create::parameters.resource, "Protected item model."); +@@doc(ProtectedItem.update::parameters.properties, "Protected item model."); +@@doc(ProtectedItem.plannedFailover::parameters.body, + "Planned failover model." +); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/RecoveryPointModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/RecoveryPointModel.tsp new file mode 100644 index 00000000000..e1454c252f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/RecoveryPointModel.tsp @@ -0,0 +1,41 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./ProtectedItemModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Recovery point model. + */ +@parentResource(ProtectedItemModel) +model RecoveryPointModel + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = RecoveryPointModel, + KeyName = "recoveryPointName", + SegmentName = "recoveryPoints", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +@armResourceOperations +interface RecoveryPoint { + /** + * Gets the details of the recovery point of a protected item. + */ + get is ArmResourceRead; + + /** + * Gets the list of recovery points of the given protected item. + */ + list is ArmResourceListByParent; +} + +@@doc(RecoveryPointModel.name, "The recovery point name."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/ReplicationExtensionModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/ReplicationExtensionModel.tsp new file mode 100644 index 00000000000..610a10deb0a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/ReplicationExtensionModel.tsp @@ -0,0 +1,60 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; +import "./VaultModel.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Replication extension model. + */ +@parentResource(VaultModel) +model ReplicationExtensionModel + is Azure.ResourceManager.ProxyResource { + ...ResourceNameParameter< + Resource = ReplicationExtensionModel, + KeyName = "replicationExtensionName", + SegmentName = "replicationExtensions", + NamePattern = "^[a-zA-Z0-9]*$" + >; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(ReplicationExtension.create::parameters.resource, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface ReplicationExtension { + /** + * Gets the details of the replication extension. + */ + get is ArmResourceRead; + + /** + * Creates the replication extension in the given vault. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Deletes the replication extension in the given vault. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the list of replication extensions in the given vault. + */ + list is ArmResourceListByParent; +} + +@@doc(ReplicationExtensionModel.name, "The replication extension name."); +@@doc(ReplicationExtension.create::parameters.resource, + "Replication extension model." +); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/VaultModel.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/VaultModel.tsp new file mode 100644 index 00000000000..69c5771a6bd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/VaultModel.tsp @@ -0,0 +1,85 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; + +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Microsoft.DataReplication; +/** + * Vault model. + */ +model VaultModel + is Azure.ResourceManager.TrackedResource { + ...ResourceNameParameter< + Resource = VaultModel, + KeyName = "vaultName", + SegmentName = "replicationVaults", + NamePattern = "^[a-zA-Z0-9]*$" + >; + ...Azure.ResourceManager.ManagedServiceIdentityProperty; +} + +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(Vault.create::parameters.resource, + "x-ms-client-name", + "body" +); +#suppress "@azure-tools/typespec-azure-core/no-openapi" +@@OpenAPI.extension(Vault.update::parameters.properties, + "x-ms-client-name", + "body" +); + +@armResourceOperations +interface Vault { + /** + * Gets the details of the vault. + */ + get is ArmResourceRead; + + /** + * Creates the vault. + */ + create is ArmResourceCreateOrReplaceAsync; + + /** + * Performs update on the vault. + */ + @patch(#{ implicitOptionality: false }) + update is ArmCustomPatchAsync; + + /** + * Removes the vault. + */ + delete is ArmResourceDeleteWithoutOkAsync; + + /** + * Gets the list of vaults in the given subscription and resource group. + */ + list is ArmResourceListByParent< + VaultModel, + { + ...Azure.ResourceManager.Foundations.BaseParameters; + + /** + * Continuation token from the previous call. + */ + @query("continuationToken") + continuationToken?: string; + } + >; + + /** + * Gets the list of vaults in the given subscription. + */ + listBySubscription is ArmListBySubscription; +} + +@@doc(VaultModel.name, "The vault name."); +@@doc(Vault.create::parameters.resource, "Vault properties."); +@@doc(Vault.update::parameters.properties, "Vault properties."); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/client.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/client.tsp new file mode 100644 index 00000000000..f520ea5ab81 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/client.tsp @@ -0,0 +1,386 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; +using Microsoft.DataReplication; + +// csharp, java don't expose LRO polling status API +@@scope(OperationResults.get, "!csharp, !java"); +@@scope(LocationBasedOperationResults.get, "!csharp, !java"); + +@@clientName(FabricAgentModelProperties.lastHeartbeat, + "LastHeartbeatOn", + "csharp" +); +@@clientName(CheckNameAvailabilityModel, + "DataReplicationNameAvailabilityContent", + "csharp" +); +@@clientName(CheckNameAvailabilityResponseModel, + "DataReplicationNameAvailabilityResult", + "csharp" +); +@@clientName(CheckNameAvailabilityResponseModel.nameAvailable, + "IsNameAvailable", + "csharp" +); +@@clientName(DeploymentPreflightResource, + "DeploymentPreflightResourceInfo", + "csharp" +); +@@clientName(EmailConfigurationModel, + "DataReplicationEmailConfiguration", + "csharp" +); +@@clientName(EmailConfigurationModelProperties, + "DataReplicationEmailConfigurationProperties", + "csharp" +); +@@clientName(ErrorModel, "DataReplicationErrorInfo", "csharp"); +@@clientName(EventModel, "DataReplicationEvent", "csharp"); +@@clientName(EventModelProperties, "DataReplicationEventProperties", "csharp"); +@@clientName(EventModelProperties.timeOfOccurrence, "OccurredOn", "csharp"); +@@clientName(EventModelCustomProperties, + "DataReplicationEventCustomProperties", + "csharp" +); +@@clientName(HyperVToAzStackHCIEventModelCustomProperties, + "HyperVToAzStackHciEventCustomProperties", + "csharp" +); +@@clientName(VMwareToAzStackHCIEventModelCustomProperties, + "VMwareToAzStackHciEventCustomProperties", + "csharp" +); +@@clientName(HealthErrorModel, "DataReplicationHealthErrorInfo", "csharp"); +@@clientName(HealthStatus, "DataReplicationHealthStatus", "csharp"); +@@clientName(IdentityModel, "DataReplicationIdentity", "csharp"); +@@clientName(InnerHealthErrorModel, + "DataReplicationInnerHealthErrorInfo", + "csharp" +); +@@clientName(PolicyModel, "DataReplicationPolicy", "csharp"); +@@clientName(PolicyModelProperties, + "DataReplicationPolicyProperties", + "csharp" +); +@@clientName(PolicyModelCustomProperties, + "DataReplicationPolicyCustomProperties", + "csharp" +); +@@clientName(VMwareToAzStackHCIPolicyModelCustomProperties, + "VMwareToAzStackHciPolicyCustomProperties", + "csharp" +); +@@clientName(ProtectedItemModel, "DataReplicationProtectedItem", "csharp"); +@@clientName(ProtectedItemModelProperties, + "DataReplicationProtectedItemProperties", + "csharp" +); +@@clientName(ProtectedItemModelProperties.resyncRequired, + "IsResyncRequired", + "csharp" +); +@@clientName(ProtectedItemModelPropertiesUpdate, + "DataReplicationProtectedItemPropertiesUpdate", + "csharp" +); +@@clientName(ProtectedItemModelCustomProperties, + "DataReplicationProtectedItemCustomProperties", + "csharp" +); +@@clientName(ProtectedItemModelCustomPropertiesUpdate, + "DataReplicationProtectedItemCustomPropertiesUpdate", + "csharp" +); +@@clientName(ProtectionState, "DataReplicationProtectionState", "csharp"); +@@clientName(ProvisioningState, "DataReplicationProvisioningState", "csharp"); +@@clientName(RecoveryPointModel, "DataReplicationRecoveryPoint", "csharp"); +@@clientName(RecoveryPointModelProperties, + "DataReplicationRecoveryPointProperties", + "csharp" +); +@@clientName(RecoveryPointModelCustomProperties, + "DataReplicationRecoveryPointCustomProperties", + "csharp" +); +@@clientName(VMwareToAzStackHCIRecoveryPointModelCustomProperties, + "VMwareToAzStackHCIRecoveryPointCustomProperties", + "csharp" +); +@@clientName(RecoveryPointType, "DataReplicationRecoveryPointType", "csharp"); +@@clientName(ReplicationExtensionModel, "DataReplicationExtension", "csharp"); +@@clientName(ReplicationExtensionModelProperties, + "DataReplicationExtensionProperties", + "csharp" +); +@@clientName(ReplicationExtensionModelCustomProperties, + "DataReplicationExtensionCustomProperties", + "csharp" +); +@@clientName(VMwareToAzStackHCIReplicationExtensionModelCustomProperties, + "VMwareToAzStackHCIReplicationExtensionCustomProperties", + "csharp" +); +@@clientName(ReplicationVaultType, "DataReplicationVaultType", "csharp"); +@@clientName(ResynchronizationState, + "DataReplicationResynchronizationState", + "csharp" +); +@@clientName(TaskModel, "DataReplicationTask", "csharp"); +@@clientName(TaskModelCustomProperties, + "DataReplicationTaskCustomProperties", + "csharp" +); +@@clientName(TaskState, "DataReplicationTaskState", "csharp"); +@@clientName(TestFailoverState, "DataReplicationTestFailoverState", "csharp"); +@@clientName(VaultModel, "DataReplicationVault", "csharp"); +@@clientName(VaultModelProperties, "DataReplicationVaultProperties", "csharp"); +@@clientName(FabricAgentModel, "DataReplicationFabricAgent", "csharp"); +@@clientName(FabricAgentModelProperties, + "DataReplicationFabricAgentProperties", + "csharp" +); +@@clientName(FabricAgentModelCustomProperties, + "DataReplicationFabricAgentCustomProperties", + "csharp" +); +@@clientName(VMwareFabricAgentModelCustomProperties, + "VMwareFabricAgentCustomProperties", + "csharp" +); +@@clientName(VMwareMigrateFabricModelCustomProperties, + "VMwareMigrateFabricCustomProperties", + "csharp" +); +@@clientName(FabricModel, "DataReplicationFabric", "csharp"); +@@clientName(FabricModelProperties, + "DataReplicationFabricProperties", + "csharp" +); +@@clientName(FabricModelCustomProperties, + "DataReplicationFabricCustomProperties", + "csharp" +); +@@clientName(AzStackHCIFabricModelCustomProperties, + "AzStackHciFabricCustomProperties", + "csharp" +); +@@clientName(HyperVMigrateFabricModelCustomProperties, + "HyperVMigrateFabricCustomProperties", + "csharp" +); +@@clientName(JobModel, "DataReplicationJob", "csharp"); +@@clientName(JobModelProperties, "DataReplicationJobProperties", "csharp"); +@@clientName(JobModelCustomProperties, + "DataReplicationJobCustomProperties", + "csharp" +); +@@clientName(FailoverJobModelCustomProperties, + "FailoverJobCustomProperties", + "csharp" +); +@@clientName(TestFailoverCleanupJobModelCustomProperties, + "TestFailoverCleanupJobCustomProperties", + "csharp" +); +@@clientName(TestFailoverJobModelCustomProperties, + "TestFailoverJobCustomProperties", + "csharp" +); +@@clientName(JobObjectType, "DataReplicationJobObjectType", "csharp"); +@@clientName(JobState, "DataReplicationJobState", "csharp"); +@@clientName(PrivateEndpointConnectionProxy, + "DataReplicationPrivateEndpointConnectionProxy", + "csharp" +); +@@clientName(PrivateEndpointConnectionProxyProperties, + "DataReplicationPrivateEndpointConnectionProxyProperties", + "csharp" +); +@@clientName(PrivateEndpointConnectionProxy, + "DataReplicationPrivateEndpointConnectionProxy", + "csharp" +); +@@clientName(PrivateEndpointConnection, + "DataReplicationPrivateEndpointConnection", + "csharp" +); +@@clientName(PrivateEndpointConnectionResponseProperties, + "DataReplicationPrivateEndpointConnectionProperties", + "csharp" +); +@@clientName(PrivateEndpointConnectionStatus, + "DataReplicationPrivateEndpointConnectionStatus", + "csharp" +); +@@clientName(PrivateLinkResource, + "DataReplicationPrivateLinkResource", + "csharp" +); +@@clientName(PrivateLinkResourceProperties, + "DataReplicationPrivateLinkResourceProperties", + "csharp" +); +@@clientName(PrivateLinkServiceConnection, + "DataReplicationPrivateLinkServiceConnection", + "csharp" +); +@@clientName(PrivateLinkServiceProxy, + "DataReplicationPrivateLinkServiceProxy", + "csharp" +); +@@clientName(PrivateLinkServiceConnectionState, + "DataReplicationPrivateLinkServiceConnectionState", + "csharp" +); +@@clientName(ConnectionDetails, + "RemotePrivateEndpointConnectionDetails", + "csharp" +); +@@clientName(DiskControllerInputs, + "DataReplicationDiskControllerInputs", + "csharp" +); +@@clientName(HyperVToAzStackHCIProtectedItemModelCustomProperties.lastRecoveryPointReceived, + "LastRecoveryPointReceivedOn", + "csharp" +); +@@clientName(VMwareToAzStackHCIProtectedItemModelCustomProperties, + "VMwareToAzStackHCIProtectedItemCustomProperties", + "csharp" +); +@@clientName(VMwareToAzStackHCIProtectedItemModelCustomProperties.lastRecoveryPointReceived, + "LastRecoveryPointReceivedOn", + "csharp" +); +@@clientName(VMwareToAzStackHCIProtectedItemModelCustomPropertiesUpdate, + "VMwareToAzStackHCIProtectedItemCustomPropertiesUpdate", + "csharp" +); +@@clientName(DeploymentPreflightModel, "DeploymentPreflight", "csharp"); +@@clientName(HyperVToAzStackHCIPolicyModelCustomProperties, + "HyperVToAzStackHciPolicyCustomProperties", + "csharp" +); +@@clientName(HyperVToAzStackHCIProtectedItemModelCustomProperties, + "HyperVToAzStackHciProtectedItemCustomProperties", + "csharp" +); +@@clientName(HyperVToAzStackHCIProtectedItemModelCustomPropertiesUpdate, + "HyperVToAzStackHciProtectedItemCustomPropertiesUpdate", + "csharp" +); +@@clientName(HyperVToAzStackHCIRecoveryPointModelCustomProperties, + "HyperVToAzStackHciRecoveryPointCustomProperties", + "csharp" +); +@@clientName(HyperVToAzStackHCIReplicationExtensionModelCustomProperties, + "HyperVToAzStackHciReplicationExtensionCustomProperties", + "csharp" +); +@@clientName(PlannedFailoverModel, "PlannedFailover", "csharp"); +@@clientName(PlannedFailoverModelProperties, + "PlannedFailoverProperties", + "csharp" +); +@@clientName(PlannedFailoverModelCustomProperties, + "PlannedFailoverCustomProperties", + "csharp" +); +@@clientName(HyperVToAzStackHCIPlannedFailoverModelCustomProperties, + "HyperVToAzStackHciPlannedFailoverCustomProperties", + "csharp" +); +@@clientName(VMwareToAzStackHCIPlannedFailoverModelCustomProperties, + "VMwareToAzStackHciPlannedFailoverCustomProperties", + "csharp" +); +@@alternateType(CheckNameAvailabilityModel.type, + Azure.Core.armResourceType, + "csharp" +); +@@alternateType(DeploymentPreflightResource.type, + Azure.Core.armResourceType, + "csharp" +); +@@alternateType(EventModelProperties.resourceType, + Azure.Core.armResourceType, + "csharp" +); +@@alternateType(HealthErrorModel.affectedResourceType, + Azure.Core.armResourceType, + "csharp" +); +@@alternateType(PrivateEndpointConnectionProxy.etag, Azure.Core.eTag, "csharp"); +@@alternateType(DeploymentPreflightResource.location, + Azure.Core.azureLocation, + "csharp" +); +@@alternateType(IdentityModel.tenantId, Azure.Core.uuid, "csharp"); +@@alternateType(AzStackHCIFabricModelCustomProperties.fabricResourceId, + Azure.Core.armResourceIdentifier, + "csharp" +); +@@alternateType(AzStackHCIFabricModelCustomProperties.fabricContainerId, + Azure.Core.armResourceIdentifier, + "csharp" +); +@@alternateType(HyperVMigrateFabricModelCustomProperties.fabricContainerId, + Azure.Core.armResourceIdentifier, + "csharp" +); + +// java, avoid model name causing file path too long +@@clientName(VMwareToAzStackHCIPlannedFailoverModelCustomProperties, + "VMwareToAzStackHciPlannedFailoverCustomProps", + "java" +); +@@clientName(VMwareToAzStackHCIReplicationExtensionModelCustomProperties, + "VMwareToAzStackHciRepExtnCustomProps", + "java" +); +@@clientName(HyperVToAzStackHCIRecoveryPointModelCustomProperties, + "HyperVToAzStackHciRecoveryPointCustomProps", + "java" +); +@@clientName(HyperVToAzStackHCIPlannedFailoverModelCustomProperties, + "HyperVToAzStackHciPlannedFailoverCustomProps", + "java" +); +@@clientName(VMwareToAzStackHCIProtectedItemModelCustomProperties, + "VMwareToAzStackHciProtectedItemCustomProps", + "java" +); +@@clientName(VMwareToAzStackHCIProtectedItemModelCustomPropertiesUpdate, + "VMwareToAzStackHciProtectedItemCustomPropsUpdate", + "java" +); +@@clientName(HyperVToAzStackHCIProtectedItemModelCustomProperties, + "HyperVToAzStackHciProtectedItemCustomProps", + "java" +); +@@clientName(HyperVToAzStackHCIProtectedItemModelCustomPropertiesUpdate, + "HyperVToAzStackHciProtectedItemCustomPropsUpdate", + "java" +); +@@clientName(HyperVToAzStackHCIReplicationExtensionModelCustomProperties, + "HyperVToAzStackHciReplicationExtCustomProps", + "java" +); +@@clientName(VMwareToAzStackHCIRecoveryPointModelCustomProperties, + "VMwareToAzStackHCIRecoveryPointCustomProps", + "java" +); +@@clientName(ReplicationExtensionModel, "ReplicationExtension", "java"); +@@clientName(PrivateEndpointConnectionProxies, + "PrivateEndpointConnProxies", + "java" +); +@@clientName(JobModelCustomProperties, "JobCustomProperties", "java"); + +@@clientName(Microsoft.DataReplication, + "RecoveryServicesDataReplicationMgmtClient", + "python" +); +@@clientName(Microsoft.DataReplication, "DataReplicationMgmtClient", "java"); diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/main.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/main.tsp new file mode 100644 index 00000000000..2e7b4678859 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/main.tsp @@ -0,0 +1,52 @@ +/** + * PLEASE DO NOT REMOVE - USED FOR CONVERTER METRICS + * Generated by package: @autorest/openapi-to-typespec + * Version: 0.8.2 + * Date: 2024-10-14T19:30:50.518Z + */ +import "@typespec/rest"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./models.tsp"; +import "./EmailConfigurationModel.tsp"; +import "./EventModel.tsp"; +import "./FabricModel.tsp"; +import "./FabricAgentModel.tsp"; +import "./JobModel.tsp"; +import "./PolicyModel.tsp"; +import "./PrivateEndpointConnection.tsp"; +import "./PrivateEndpointConnectionProxy.tsp"; +import "./PrivateLinkResource.tsp"; +import "./ProtectedItemModel.tsp"; +import "./RecoveryPointModel.tsp"; +import "./ReplicationExtensionModel.tsp"; +import "./VaultModel.tsp"; +import "./routes.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager.Foundations; +using Azure.Core; +using Azure.ResourceManager; +using TypeSpec.Versioning; +/** + * A first party Azure service enabling the data replication. + */ +@armProviderNamespace +@service(#{ title: "Azure Site Recovery Management Service API" }) +@versioned(Versions) +@armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v6) +namespace Microsoft.DataReplication; + +/** + * The available API versions. + */ +enum Versions { + /** + * The 2024-09-01 API version. + */ + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(Azure.Core.Versions.v1_0_Preview_1) + v2024_09_01: "2024-09-01", +} diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/models.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/models.tsp new file mode 100644 index 00000000000..79ddac81f6b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/models.tsp @@ -0,0 +1,4228 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; + +namespace Microsoft.DataReplication; + +interface Operations extends Azure.ResourceManager.Operations {} + +/** + * Gets or sets the provisioning state of the email configuration. + */ +union ProvisioningState { + string, + + /** + * Resource creation has been canceled + */ + Canceled: "Canceled", + + /** + * Resource is being created. + */ + Creating: "Creating", + + /** + * Resource is being deleted. + */ + Deleting: "Deleting", + + /** + * Resource has been deleted. + */ + Deleted: "Deleted", + + /** + * Resource creation failed. + */ + Failed: "Failed", + + /** + * Resource creation/update succeeded. + */ + Succeeded: "Succeeded", + + /** + * Resource is being updated. + */ + Updating: "Updating", +} + +/** + * Gets or sets the fabric health. + */ +union HealthStatus { + string, + + /** + * Healthy Status. + */ + Normal: "Normal", + + /** + * Warning Status. + */ + Warning: "Warning", + + /** + * Critical Status. + */ + Critical: "Critical", +} + +/** + * Gets or sets the job state. + */ +union JobState { + string, + + /** + * Job has not been started. + */ + Pending: "Pending", + + /** + * Job is in progress. + */ + Started: "Started", + + /** + * Job cancellation is in progress. + */ + Cancelling: "Cancelling", + + /** + * Job has completed successfully. + */ + Succeeded: "Succeeded", + + /** + * Job failed. + */ + Failed: "Failed", + + /** + * Job has been cancelled. + */ + Cancelled: "Cancelled", + + /** + * Job has completed with information. + */ + CompletedWithInformation: "CompletedWithInformation", + + /** + * Job has completed with warnings. + */ + CompletedWithWarnings: "CompletedWithWarnings", + + /** + * Job has completed with errors. + */ + CompletedWithErrors: "CompletedWithErrors", +} + +/** + * Gets or sets the object type. + */ +union JobObjectType { + string, + + /** + * AVS disk pool. + */ + AvsDiskPool: "AvsDiskPool", + + /** + * Fabric agent level workflow. + */ + FabricAgent: "FabricAgent", + + /** + * Fabric level job. + */ + Fabric: "Fabric", + + /** + * Policy level job. + */ + Policy: "Policy", + + /** + * Protected item level job. + */ + ProtectedItem: "ProtectedItem", + + /** + * Recovery plan level job. + */ + RecoveryPlan: "RecoveryPlan", + + /** + * Replication extension level job. + */ + ReplicationExtension: "ReplicationExtension", + + /** + * Vault level job. + */ + Vault: "Vault", +} + +/** + * Gets or sets the task state. + */ +union TaskState { + string, + + /** + * Task has not been started. + */ + Pending: "Pending", + + /** + * Task is in progress. + */ + Started: "Started", + + /** + * Task has completed successfully. + */ + Succeeded: "Succeeded", + + /** + * Task failed. + */ + Failed: "Failed", + + /** + * Task has been cancelled. + */ + Cancelled: "Cancelled", + + /** + * Task has been skipped. + */ + Skipped: "Skipped", +} + +/** + * Gets or sets the status. + */ +union PrivateEndpointConnectionStatus { + string, + + /** + * Approved Status. + */ + Approved: "Approved", + + /** + * Disconnected Status. + */ + Disconnected: "Disconnected", + + /** + * Pending Status. + */ + Pending: "Pending", + + /** + * Rejected Status. + */ + Rejected: "Rejected", +} + +/** + * Gets or sets the protection state. + */ +union ProtectionState { + string, + + /** + * Begin marker for unprotected states. + */ + UnprotectedStatesBegin: "UnprotectedStatesBegin", + + /** + * Enable protection is in progress. + */ + EnablingProtection: "EnablingProtection", + + /** + * Enable protection failed. + */ + EnablingFailed: "EnablingFailed", + + /** + * Disabling protection is in progress. + */ + DisablingProtection: "DisablingProtection", + + /** + * Disabling protection succeeded. This is a transient state before the protected item is deleted. + */ + MarkedForDeletion: "MarkedForDeletion", + + /** + * Disable protection failed. + */ + DisablingFailed: "DisablingFailed", + + /** + * End marker for unprotected states. + */ + UnprotectedStatesEnd: "UnprotectedStatesEnd", + + /** + * Begin marker for initial replication states. + */ + InitialReplicationStatesBegin: "InitialReplicationStatesBegin", + + /** + * Initial replication is in progress. + */ + InitialReplicationInProgress: "InitialReplicationInProgress", + + /** + * Initial replication has completed on the primary side. + */ + InitialReplicationCompletedOnPrimary: "InitialReplicationCompletedOnPrimary", + + /** + * Initial replication has completed on the recovery side. + */ + InitialReplicationCompletedOnRecovery: "InitialReplicationCompletedOnRecovery", + + /** + * Initial replication failed and would need to be started again. + */ + InitialReplicationFailed: "InitialReplicationFailed", + + /** + * End marker for initial replication states. + */ + InitialReplicationStatesEnd: "InitialReplicationStatesEnd", + + /** + * Begin marker for protected steady-state states. + */ + ProtectedStatesBegin: "ProtectedStatesBegin", + + /** + * Protected item is protected and replication is on-going. Any issues with replication will be surfaced separately via the health property and will not affect the state. + */ + Protected: "Protected", + + /** + * End marker for protected steady-state states. + */ + ProtectedStatesEnd: "ProtectedStatesEnd", + + /** + * Begin marker for planned failover transition states. + */ + PlannedFailoverTransitionStatesBegin: "PlannedFailoverTransitionStatesBegin", + + /** + * Planned failover has been initiated. + */ + PlannedFailoverInitiated: "PlannedFailoverInitiated", + + /** + * Planned failover preparing protected entities is in progress. + */ + PlannedFailoverCompleting: "PlannedFailoverCompleting", + + /** + * Planned failover has been completed successfully. + */ + PlannedFailoverCompleted: "PlannedFailoverCompleted", + + /** + * Planned failover initiation failed. + */ + PlannedFailoverFailed: "PlannedFailoverFailed", + + /** + * Planned failover preparing protected entities failed. + */ + PlannedFailoverCompletionFailed: "PlannedFailoverCompletionFailed", + + /** + * End marker for planned failover transition states. + */ + PlannedFailoverTransitionStatesEnd: "PlannedFailoverTransitionStatesEnd", + + /** + * Begin marker for unplanned failover transition states. + */ + UnplannedFailoverTransitionStatesBegin: "UnplannedFailoverTransitionStatesBegin", + + /** + * Unplanned failover has been initiated. + */ + UnplannedFailoverInitiated: "UnplannedFailoverInitiated", + + /** + * Unplanned failover preparing protected entities is in progress. + */ + UnplannedFailoverCompleting: "UnplannedFailoverCompleting", + + /** + * Unplanned failover preparing protected entities is in progress. + */ + UnplannedFailoverCompleted: "UnplannedFailoverCompleted", + + /** + * Unplanned failover initiation failed. + */ + UnplannedFailoverFailed: "UnplannedFailoverFailed", + + /** + * Unplanned failover preparing protected entities failed. + */ + UnplannedFailoverCompletionFailed: "UnplannedFailoverCompletionFailed", + + /** + * End marker for unplanned failover transition states. + */ + UnplannedFailoverTransitionStatesEnd: "UnplannedFailoverTransitionStatesEnd", + + /** + * Begin marker for commit failover states. + */ + CommitFailoverStatesBegin: "CommitFailoverStatesBegin", + + /** + * Commit failover is in progress on the primary side. + */ + CommitFailoverInProgressOnPrimary: "CommitFailoverInProgressOnPrimary", + + /** + * Commit failover is in progress on the recovery side. + */ + CommitFailoverInProgressOnRecovery: "CommitFailoverInProgressOnRecovery", + + /** + * Commit failover has been completed successfully. + */ + CommitFailoverCompleted: "CommitFailoverCompleted", + + /** + * Commit failover failed on the primary side. + */ + CommitFailoverFailedOnPrimary: "CommitFailoverFailedOnPrimary", + + /** + * Commit failover failed on the recovery side. + */ + CommitFailoverFailedOnRecovery: "CommitFailoverFailedOnRecovery", + + /** + * End marker for commit failover states. + */ + CommitFailoverStatesEnd: "CommitFailoverStatesEnd", + + /** + * Begin marker for cancel failover states. + */ + CancelFailoverStatesBegin: "CancelFailoverStatesBegin", + + /** + * Cancel failover is in progress on the primary side. + */ + CancelFailoverInProgressOnPrimary: "CancelFailoverInProgressOnPrimary", + + /** + * Cancel failover is in progress on the recovery side. + */ + CancelFailoverInProgressOnRecovery: "CancelFailoverInProgressOnRecovery", + + /** + * Cancel failover failed on the primary side. + */ + CancelFailoverFailedOnPrimary: "CancelFailoverFailedOnPrimary", + + /** + * Cancel failover failed on the recovery side. + */ + CancelFailoverFailedOnRecovery: "CancelFailoverFailedOnRecovery", + + /** + * End marker for cancel failover states. + */ + CancelFailoverStatesEnd: "CancelFailoverStatesEnd", + + /** + * Begin marker for change recovery point states. + */ + ChangeRecoveryPointStatesBegin: "ChangeRecoveryPointStatesBegin", + + /** + * Change recovery point has been initiated.. + */ + ChangeRecoveryPointInitiated: "ChangeRecoveryPointInitiated", + + /** + * Change recovery point has been completed successfully. + */ + ChangeRecoveryPointCompleted: "ChangeRecoveryPointCompleted", + + /** + * Change recovery point has failed. + */ + ChangeRecoveryPointFailed: "ChangeRecoveryPointFailed", + + /** + * End marker for change recovery point states. + */ + ChangeRecoveryPointStatesEnd: "ChangeRecoveryPointStatesEnd", + + /** + * Begin marker for reprotect states. + */ + ReprotectStatesBegin: "ReprotectStatesBegin", + + /** + * Reprotect has been initiated. + */ + ReprotectInitiated: "ReprotectInitiated", + + /** + * Reprotect has failed. + */ + ReprotectFailed: "ReprotectFailed", + + /** + * End marker for reprotect states. + */ + ReprotectStatesEnd: "ReprotectStatesEnd", +} + +/** + * Gets or sets the test failover state. + */ +union TestFailoverState { + string, + + /** + * Test failover is not active. + */ + None: "None", + + /** + * Test failover has been initiated. + */ + TestFailoverInitiated: "TestFailoverInitiated", + + /** + * Preparing test protected entities is in progress. + */ + TestFailoverCompleting: "TestFailoverCompleting", + + /** + * Test failover has been completed successfully. + */ + TestFailoverCompleted: "TestFailoverCompleted", + + /** + * Test failover initiation failed.. + */ + TestFailoverFailed: "TestFailoverFailed", + + /** + * Preparing test protected entities failed. + */ + TestFailoverCompletionFailed: "TestFailoverCompletionFailed", + + /** + * Test failover cleanup has been initiated. + */ + TestFailoverCleanupInitiated: "TestFailoverCleanupInitiated", + + /** + * Cleaning up test protected entities is in progress. + */ + TestFailoverCleanupCompleting: "TestFailoverCleanupCompleting", + + /** + * Test failover cleanup has completed/failed. This is a transient state before the state is moved back to None. + */ + MarkedForDeletion: "MarkedForDeletion", +} + +/** + * Gets or sets the resynchronization state. + */ +union ResynchronizationState { + string, + + /** + * Resynchronization is not active. + */ + None: "None", + + /** + * Resynchronization has been initiated. + */ + ResynchronizationInitiated: "ResynchronizationInitiated", + + /** + * Resynchronization has been completed successfully. + */ + ResynchronizationCompleted: "ResynchronizationCompleted", + + /** + * Resynchronization has failed and would need to be started again. + */ + ResynchronizationFailed: "ResynchronizationFailed", +} + +/** + * Gets or sets the recovery point type. + */ +union RecoveryPointType { + string, + + /** + * Application consistent recovery point. + */ + ApplicationConsistent: "ApplicationConsistent", + + /** + * Crash consistent recovery point. + */ + CrashConsistent: "CrashConsistent", +} + +/** + * Gets or sets the type of vault. + */ +union ReplicationVaultType { + string, + + /** + * Disaster recovery vault. + */ + DisasterRecovery: "DisasterRecovery", + + /** + * Migrate vault. + */ + Migrate: "Migrate", +} + +/** + * Gets or sets the identityType which can be either SystemAssigned or None. + */ +union VaultIdentityType { + string, + + /** + * No identity. + */ + None: "None", + + /** + * System assigned identity. + */ + SystemAssigned: "SystemAssigned", + + /** + * User assigned identity. + */ + UserAssigned: "UserAssigned", +} + +/** + * Gets or sets the selection type of the NIC. + */ +union VMNicSelection { + string, + + /** + * Not Selected. + */ + NotSelected: "NotSelected", + + /** + * Selected by user. + */ + SelectedByUser: "SelectedByUser", + + /** + * Default selection by ASR. + */ + SelectedByDefault: "SelectedByDefault", + + /** + * NIC configuration overridden by user. Differs from SelectedByUser in the sense that the legacy SelectedByUser is used both for explicit modification by user and implicit approval of user if the settings are used for TFO/FO. SelectedByUserOverride implies user overriding at least one of the configurations. + */ + SelectedByUserOverride: "SelectedByUserOverride", +} + +/** + * Gets or sets the location of the protected item. + */ +union ProtectedItemActiveLocation { + string, + + /** + * Protected item is active on Primary. + */ + Primary: "Primary", + + /** + * Protected item is active on Recovery. + */ + Recovery: "Recovery", +} + +/** + * Gets or sets the resync state. + */ +union VMwareToAzureMigrateResyncState { + string, + + /** + * None state. + */ + None: "None", + + /** + * Prepared for resynchronization state. + */ + PreparedForResynchronization: "PreparedForResynchronization", + + /** + * Started resynchronization state. + */ + StartedResynchronization: "StartedResynchronization", +} + +/** + * Email configuration model properties. + */ +model EmailConfigurationModelProperties { + /** + * Gets or sets a value indicating whether to send email to subscription administrator. + */ + sendToOwners: boolean; + + /** + * Gets or sets the custom email address for sending emails. + */ + customEmailAddresses?: string[]; + + /** + * Gets or sets the locale for the email notification. + */ + locale?: string; + + /** + * Gets or sets the provisioning state of the email configuration. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Event model properties. + */ +model EventModelProperties { + /** + * Gets or sets the resource type. + */ + @visibility(Lifecycle.Read) + resourceType?: string; + + /** + * Gets or sets the resource name. + */ + @visibility(Lifecycle.Read) + resourceName?: string; + + /** + * Gets or sets the event type. + */ + @visibility(Lifecycle.Read) + eventType?: string; + + /** + * Gets or sets the event name. + */ + @visibility(Lifecycle.Read) + eventName?: string; + + /** + * Gets or sets the time at which the event occurred at source. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + timeOfOccurrence?: utcDateTime; + + /** + * Gets or sets the event severity. + */ + @visibility(Lifecycle.Read) + severity?: string; + + /** + * Gets or sets the event description. + */ + @visibility(Lifecycle.Read) + description?: string; + + /** + * Gets or sets the event correlation Id. + */ + @visibility(Lifecycle.Read) + correlationId?: string; + + /** + * Gets or sets the errors associated with this event. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + healthErrors?: HealthErrorModel[]; + + /** + * Event model custom properties. + */ + customProperties: EventModelCustomProperties; + + /** + * Gets or sets the provisioning state of the event. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Health error model. + */ +model HealthErrorModel { + /** + * Gets or sets the type of affected resource type. + */ + affectedResourceType?: string; + + /** + * Gets or sets the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected by a specific category and severity as well as count of item affected by an specific issue. + */ + affectedResourceCorrelationIds?: string[]; + + /** + * Gets or sets a list of child health errors associated with this error. + */ + @identifiers(#[]) + childErrors?: InnerHealthErrorModel[]; + + /** + * Gets or sets the error code. + */ + @visibility(Lifecycle.Read) + code?: string; + + /** + * Gets or sets the health category. + */ + @visibility(Lifecycle.Read) + healthCategory?: string; + + /** + * Gets or sets the error category. + */ + @visibility(Lifecycle.Read) + category?: string; + + /** + * Gets or sets the error severity. + */ + @visibility(Lifecycle.Read) + severity?: string; + + /** + * Gets or sets the error source. + */ + @visibility(Lifecycle.Read) + source?: string; + + /** + * Gets or sets the error creation time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + creationTime?: utcDateTime; + + /** + * Gets or sets a value indicating whether the error is customer resolvable. + */ + @visibility(Lifecycle.Read) + isCustomerResolvable?: boolean; + + /** + * Gets or sets the error summary. + */ + @visibility(Lifecycle.Read) + summary?: string; + + /** + * Gets or sets the error message. + */ + @visibility(Lifecycle.Read) + message?: string; + + /** + * Gets or sets possible causes of the error. + */ + @visibility(Lifecycle.Read) + causes?: string; + + /** + * Gets or sets recommended action to resolve the error. + */ + @visibility(Lifecycle.Read) + recommendation?: string; +} + +/** + * Inner health error model. + */ +model InnerHealthErrorModel { + /** + * Gets or sets the error code. + */ + @visibility(Lifecycle.Read) + code?: string; + + /** + * Gets or sets the health category. + */ + @visibility(Lifecycle.Read) + healthCategory?: string; + + /** + * Gets or sets the error category. + */ + @visibility(Lifecycle.Read) + category?: string; + + /** + * Gets or sets the error severity. + */ + @visibility(Lifecycle.Read) + severity?: string; + + /** + * Gets or sets the error source. + */ + @visibility(Lifecycle.Read) + source?: string; + + /** + * Gets or sets the error creation time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + creationTime?: utcDateTime; + + /** + * Gets or sets a value indicating whether the error is customer resolvable. + */ + @visibility(Lifecycle.Read) + isCustomerResolvable?: boolean; + + /** + * Gets or sets the error summary. + */ + @visibility(Lifecycle.Read) + summary?: string; + + /** + * Gets or sets the error message. + */ + @visibility(Lifecycle.Read) + message?: string; + + /** + * Gets or sets possible causes of the error. + */ + @visibility(Lifecycle.Read) + causes?: string; + + /** + * Gets or sets recommended action to resolve the error. + */ + @visibility(Lifecycle.Read) + recommendation?: string; +} + +/** + * Event model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model EventModelCustomProperties {} + +/** + * Fabric model properties. + */ +model FabricModelProperties { + /** + * Gets or sets the provisioning state of the fabric. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Gets or sets the service endpoint. + */ + @visibility(Lifecycle.Read) + serviceEndpoint?: string; + + /** + * Gets or sets the service resource Id. + */ + @visibility(Lifecycle.Read) + serviceResourceId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the fabric health. + */ + @visibility(Lifecycle.Read) + health?: HealthStatus; + + /** + * Gets or sets the list of health errors. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + healthErrors?: HealthErrorModel[]; + + /** + * Fabric model custom properties. + */ + customProperties: FabricModelCustomProperties; +} + +/** + * Fabric model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model FabricModelCustomProperties {} + +/** + * Fabric model update. + */ +model FabricModelUpdate { + /** + * Gets or sets the resource tags. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" + tags?: Record; + + /** + * Fabric model properties. + */ + properties?: FabricModelProperties; + + /** + * Gets or sets the Id of the resource. + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * Gets or sets the name of the resource. + */ + @visibility(Lifecycle.Read) + name?: string; + + /** + * Gets or sets the type of the resource. + */ + @visibility(Lifecycle.Read) + type?: string; + + /** + * Metadata pertaining to creation and last modification of the resource. + */ + @visibility(Lifecycle.Read) + systemData?: SystemData; +} + +/** + * Fabric agent model properties. + */ +model FabricAgentModelProperties { + /** + * Gets or sets the fabric agent correlation Id. + */ + @visibility(Lifecycle.Read) + correlationId?: string; + + /** + * Gets or sets the machine Id where fabric agent is running. + */ + @minLength(1) + machineId: string; + + /** + * Gets or sets the machine name where fabric agent is running. + */ + @minLength(1) + machineName: string; + + /** + * Identity model. + */ + authenticationIdentity: IdentityModel; + + /** + * Identity model. + */ + resourceAccessIdentity: IdentityModel; + + /** + * Gets or sets a value indicating whether the fabric agent is responsive. + */ + @visibility(Lifecycle.Read) + isResponsive?: boolean; + + /** + * Gets or sets the time when last heartbeat was sent by the fabric agent. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastHeartbeat?: utcDateTime; + + /** + * Gets or sets the fabric agent version. + */ + @visibility(Lifecycle.Read) + versionNumber?: string; + + /** + * Gets or sets the provisioning state of the fabric agent. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Gets or sets the list of health errors. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + healthErrors?: HealthErrorModel[]; + + /** + * Fabric agent model custom properties. + */ + customProperties: FabricAgentModelCustomProperties; +} + +/** + * Identity model. + */ +model IdentityModel { + /** + * Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + */ + @minLength(1) + tenantId: string; + + /** + * Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + */ + @minLength(1) + applicationId: string; + + /** + * Gets or sets the object Id of the SPN with which fabric agent communicates to service. + */ + @minLength(1) + objectId: string; + + /** + * Gets or sets the audience of the SPN with which fabric agent communicates to service. + */ + @minLength(1) + audience: string; + + /** + * Gets or sets the authority of the SPN with which fabric agent communicates to service. + */ + @minLength(1) + aadAuthority: string; +} + +/** + * Fabric agent model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model FabricAgentModelCustomProperties {} + +/** + * Job model properties. + */ +model JobModelProperties { + /** + * Gets or sets the friendly display name. + */ + @visibility(Lifecycle.Read) + displayName?: string; + + /** + * Gets or sets the job state. + */ + @visibility(Lifecycle.Read) + state?: JobState; + + /** + * Gets or sets the start time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + startTime?: utcDateTime; + + /** + * Gets or sets the end time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + endTime?: utcDateTime; + + /** + * Gets or sets the affected object Id. + */ + @visibility(Lifecycle.Read) + objectId?: string; + + /** + * Gets or sets the affected object name. + */ + @visibility(Lifecycle.Read) + objectName?: string; + + /** + * Gets or sets the affected object internal Id. + */ + @visibility(Lifecycle.Read) + objectInternalId?: string; + + /** + * Gets or sets the affected object internal name. + */ + @visibility(Lifecycle.Read) + objectInternalName?: string; + + /** + * Gets or sets the object type. + */ + @visibility(Lifecycle.Read) + objectType?: JobObjectType; + + /** + * Gets or sets the replication provider. + */ + @visibility(Lifecycle.Read) + replicationProviderId?: string; + + /** + * Gets or sets the source fabric provider. + */ + @visibility(Lifecycle.Read) + sourceFabricProviderId?: string; + + /** + * Gets or sets the target fabric provider. + */ + @visibility(Lifecycle.Read) + targetFabricProviderId?: string; + + /** + * Gets or sets the list of allowed actions on the job. + */ + @visibility(Lifecycle.Read) + allowedActions?: string[]; + + /** + * Gets or sets the job activity id. + */ + @visibility(Lifecycle.Read) + activityId?: string; + + /** + * Gets or sets the list of tasks. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + tasks?: TaskModel[]; + + /** + * Gets or sets the list of errors. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + errors?: ErrorModel[]; + + /** + * Job model custom properties. + */ + customProperties: JobModelCustomProperties; + + /** + * Gets or sets the provisioning state of the job. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Task model. + */ +model TaskModel { + /** + * Gets or sets the task name. + */ + @visibility(Lifecycle.Read) + taskName?: string; + + /** + * Gets or sets the task state. + */ + @visibility(Lifecycle.Read) + state?: TaskState; + + /** + * Gets or sets the start time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + startTime?: utcDateTime; + + /** + * Gets or sets the end time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + endTime?: utcDateTime; + + /** + * Task model custom properties. + */ + customProperties?: TaskModelCustomProperties; + + /** + * Gets or sets the list of children job models. + */ + @identifiers(#[]) + childrenJobs?: JobModel[]; +} + +/** + * Task model custom properties. + */ +model TaskModelCustomProperties { + /** + * Gets or sets the instance type. + */ + @minLength(1) + instanceType: string; +} + +/** + * Error model. + */ +model ErrorModel { + /** + * Gets or sets the error code. + */ + @visibility(Lifecycle.Read) + code?: string; + + /** + * Gets or sets the error type. + */ + @visibility(Lifecycle.Read) + type?: string; + + /** + * Gets or sets the error severity. + */ + @visibility(Lifecycle.Read) + severity?: string; + + /** + * Gets or sets the creation time of error. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + creationTime?: utcDateTime; + + /** + * Gets or sets the error message. + */ + @visibility(Lifecycle.Read) + message?: string; + + /** + * Gets or sets the possible causes of error. + */ + @visibility(Lifecycle.Read) + causes?: string; + + /** + * Gets or sets the recommended action to resolve error. + */ + @visibility(Lifecycle.Read) + recommendation?: string; +} + +/** + * Job model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +@discriminator("instanceType") +model JobModelCustomProperties { + /** + * Gets or sets any custom properties of the affected object. + */ + @visibility(Lifecycle.Read) + affectedObjectDetails?: AffectedObjectDetails; +} + +/** + * Details of the affected object. + */ +model AffectedObjectDetails { + /** + * Description of the affected object details. + */ + description?: string; + + /** + * Type of the affected object details. + */ + type?: "object"; +} + +/** + * Policy model properties. + */ +model PolicyModelProperties { + /** + * Gets or sets the provisioning state of the policy. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Policy model custom properties. + */ + customProperties: PolicyModelCustomProperties; +} + +/** + * Policy model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model PolicyModelCustomProperties {} + +/** + * Represents Private endpoint connection response properties. + */ +model PrivateEndpointConnectionResponseProperties { + /** + * Gets or sets provisioning state of the private endpoint connection. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Represent private Endpoint network resource that is linked to the Private Endpoint connection. + */ + privateEndpoint?: PrivateEndpoint; + + /** + * Represents Private link service connection state. + */ + privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; +} + +/** + * Represent private Endpoint network resource that is linked to the Private Endpoint connection. + */ +model PrivateEndpoint { + /** + * Gets or sets the id. + */ + id?: string; +} + +/** + * Represents Private link service connection state. + */ +model PrivateLinkServiceConnectionState { + /** + * Gets or sets the status. + */ + status?: PrivateEndpointConnectionStatus; + + /** + * Gets or sets description. + */ + description?: string; + + /** + * Gets or sets actions required. + */ + actionsRequired?: string; +} + +/** + * Represents private endpoint connection proxy request. + */ +model PrivateEndpointConnectionProxyProperties { + /** + * Gets or sets the provisioning state of the private endpoint connection proxy. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Represent remote private endpoint information for the private endpoint connection proxy. + */ + remotePrivateEndpoint?: RemotePrivateEndpoint; +} + +/** + * Represent remote private endpoint information for the private endpoint connection proxy. + */ +model RemotePrivateEndpoint { + /** + * Gets or sets private link service proxy id. + */ + @minLength(1) + id: string; + + /** + * Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + */ + @identifiers(#[]) + privateLinkServiceConnections?: PrivateLinkServiceConnection[]; + + /** + * Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + */ + @identifiers(#[]) + manualPrivateLinkServiceConnections?: PrivateLinkServiceConnection[]; + + /** + * Gets or sets the list of private link service proxies. + */ + @identifiers(#[]) + privateLinkServiceProxies?: PrivateLinkServiceProxy[]; + + /** + * Gets or sets the list of Connection Details. This is the connection details for private endpoint. + */ + @identifiers(#[]) + connectionDetails?: ConnectionDetails[]; +} + +/** + * Represents of an NRP private link service connection. + */ +model PrivateLinkServiceConnection { + /** + * Gets or sets private link service connection name. + */ + name?: string; + + /** + * Gets or sets group ids. + */ + groupIds?: string[]; + + /** + * Gets or sets the request message for the private link service connection. + */ + requestMessage?: string; +} + +/** + * Represents NRP private link service proxy. + */ +model PrivateLinkServiceProxy { + /** + * Gets or sets private link service proxy id. + */ + id?: string; + + /** + * Represents Private link service connection state. + */ + remotePrivateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; + + /** + * Represent remote private endpoint connection. + */ + remotePrivateEndpointConnection?: RemotePrivateEndpointConnection; + + /** + * Gets or sets group connectivity information. + */ + @identifiers(#[]) + groupConnectivityInformation?: GroupConnectivityInformation[]; +} + +/** + * Represent remote private endpoint connection. + */ +model RemotePrivateEndpointConnection { + /** + * Gets or sets the remote private endpoint connection id. + */ + id?: string; +} + +/** + * Represents of a connection's group information. + */ +model GroupConnectivityInformation { + /** + * Gets or sets group id. + */ + groupId?: string; + + /** + * Gets or sets member name. + */ + memberName?: string; + + /** + * Gets or sets customer visible FQDNs. + */ + customerVisibleFqdns?: string[]; + + /** + * Gets or sets Internal Fqdn. + */ + internalFqdn?: string; + + /** + * Gets or sets the redirect map id. + */ + redirectMapId?: string; + + /** + * Gets or sets the private link service arm region. + */ + privateLinkServiceArmRegion?: string; +} + +/** + * Private endpoint connection details at member level. + */ +model ConnectionDetails { + /** + * Gets or sets id. + */ + id?: string; + + /** + * Gets or sets private IP address. + */ + privateIpAddress?: string; + + /** + * Gets or sets link identifier. + */ + linkIdentifier?: string; + + /** + * Gets or sets group id. + */ + groupId?: string; + + /** + * Gets or sets member name. + */ + memberName?: string; +} + +/** + * Represents private link resource properties. + */ +model PrivateLinkResourceProperties { + /** + * Gets or sets the group id. + */ + groupId?: string; + + /** + * Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable resource. + */ + requiredMembers?: string[]; + + /** + * Gets or sets the private DNS zone names. + */ + requiredZoneNames?: string[]; + + /** + * Gets or sets the provisioning state of the private link resource. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Protected item model properties. + */ +model ProtectedItemModelProperties { + /** + * Gets or sets the policy name. + */ + @minLength(1) + policyName: string; + + /** + * Gets or sets the replication extension name. + */ + @minLength(1) + replicationExtensionName: string; + + /** + * Gets or sets the protected item correlation Id. + */ + @visibility(Lifecycle.Read) + correlationId?: string; + + /** + * Gets or sets the provisioning state of the fabric agent. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Gets or sets the protection state. + */ + @visibility(Lifecycle.Read) + protectionState?: ProtectionState; + + /** + * Gets or sets the protection state description. + */ + @visibility(Lifecycle.Read) + protectionStateDescription?: string; + + /** + * Gets or sets the test failover state. + */ + @visibility(Lifecycle.Read) + testFailoverState?: TestFailoverState; + + /** + * Gets or sets the Test failover state description. + */ + @visibility(Lifecycle.Read) + testFailoverStateDescription?: string; + + /** + * Gets or sets the resynchronization state. + */ + @visibility(Lifecycle.Read) + resynchronizationState?: ResynchronizationState; + + /** + * Gets or sets the fabric object Id. + */ + @visibility(Lifecycle.Read) + fabricObjectId?: string; + + /** + * Gets or sets the fabric object name. + */ + @visibility(Lifecycle.Read) + fabricObjectName?: string; + + /** + * Gets or sets the source fabric provider Id. + */ + @visibility(Lifecycle.Read) + sourceFabricProviderId?: string; + + /** + * Gets or sets the target fabric provider Id. + */ + @visibility(Lifecycle.Read) + targetFabricProviderId?: string; + + /** + * Gets or sets the fabric Id. + */ + @visibility(Lifecycle.Read) + fabricId?: string; + + /** + * Gets or sets the target fabric Id. + */ + @visibility(Lifecycle.Read) + targetFabricId?: string; + + /** + * Gets or sets the fabric agent Id. + */ + @visibility(Lifecycle.Read) + fabricAgentId?: string; + + /** + * Gets or sets the target fabric agent Id. + */ + @visibility(Lifecycle.Read) + targetFabricAgentId?: string; + + /** + * Gets or sets a value indicating whether resynchronization is required or not. + */ + @visibility(Lifecycle.Read) + resyncRequired?: boolean; + + /** + * Gets or sets the Last successful planned failover time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastSuccessfulPlannedFailoverTime?: utcDateTime; + + /** + * Gets or sets the Last successful unplanned failover time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastSuccessfulUnplannedFailoverTime?: utcDateTime; + + /** + * Gets or sets the Last successful test failover time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastSuccessfulTestFailoverTime?: utcDateTime; + + /** + * Gets or sets the current scenario. + */ + @visibility(Lifecycle.Read) + currentJob?: ProtectedItemJobProperties; + + /** + * Gets or sets the allowed scenarios on the protected item. + */ + @visibility(Lifecycle.Read) + allowedJobs?: string[]; + + /** + * Gets or sets the last failed enabled protection job. + */ + @visibility(Lifecycle.Read) + lastFailedEnableProtectionJob?: ProtectedItemJobProperties; + + /** + * Gets or sets the last failed planned failover job. + */ + @visibility(Lifecycle.Read) + lastFailedPlannedFailoverJob?: ProtectedItemJobProperties; + + /** + * Gets or sets the last test failover job. + */ + @visibility(Lifecycle.Read) + lastTestFailoverJob?: ProtectedItemJobProperties; + + /** + * Gets or sets protected item replication health. + */ + @visibility(Lifecycle.Read) + replicationHealth?: HealthStatus; + + /** + * Gets or sets the list of health errors. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + healthErrors?: HealthErrorModel[]; + + /** + * Protected item model custom properties. + */ + customProperties: ProtectedItemModelCustomProperties; +} + +/** + * Protected item job properties. + */ +model ProtectedItemJobProperties { + /** + * Gets or sets protection scenario name. + */ + @visibility(Lifecycle.Read) + scenarioName?: string; + + /** + * Gets or sets job Id. + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * Gets or sets job name. + */ + @visibility(Lifecycle.Read) + name?: string; + + /** + * Gets or sets the job friendly display name. + */ + @visibility(Lifecycle.Read) + displayName?: string; + + /** + * Gets or sets job state. + */ + @visibility(Lifecycle.Read) + state?: string; + + /** + * Gets or sets start time of the job. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + startTime?: utcDateTime; + + /** + * Gets or sets end time of the job. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + endTime?: utcDateTime; +} + +/** + * Protected item model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model ProtectedItemModelCustomProperties {} + +/** + * Protected item model update. + */ +model ProtectedItemModelUpdate { + /** + * Protected item model properties. + */ + properties?: ProtectedItemModelPropertiesUpdate; + + /** + * Gets or sets the Id of the resource. + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * Gets or sets the name of the resource. + */ + @visibility(Lifecycle.Read) + name?: string; + + /** + * Gets or sets the type of the resource. + */ + @visibility(Lifecycle.Read) + type?: string; + + /** + * Metadata pertaining to creation and last modification of the resource. + */ + @visibility(Lifecycle.Read) + systemData?: SystemData; +} + +/** + * Protected item model properties update. + */ +model ProtectedItemModelPropertiesUpdate { + /** + * Protected item model custom properties update. + */ + customProperties?: ProtectedItemModelCustomPropertiesUpdate; +} + +/** + * Protected item model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model ProtectedItemModelCustomPropertiesUpdate {} + +/** + * Planned failover model. + */ +model PlannedFailoverModel { + /** + * Planned failover model properties. + */ + properties: PlannedFailoverModelProperties; +} + +/** + * Planned failover model properties. + */ +model PlannedFailoverModelProperties { + /** + * Planned failover model custom properties. + */ + customProperties: PlannedFailoverModelCustomProperties; +} + +/** + * Planned failover model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model PlannedFailoverModelCustomProperties {} + +/** + * Recovery point model properties. + */ +model RecoveryPointModelProperties { + /** + * Gets or sets the recovery point time. + */ + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + recoveryPointTime: utcDateTime; + + /** + * Gets or sets the recovery point type. + */ + recoveryPointType: RecoveryPointType; + + /** + * Recovery point model custom properties. + */ + customProperties: RecoveryPointModelCustomProperties; + + /** + * Gets or sets the provisioning state of the recovery point item. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; +} + +/** + * Recovery point model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model RecoveryPointModelCustomProperties {} + +/** + * Replication extension model properties. + */ +model ReplicationExtensionModelProperties { + /** + * Gets or sets the provisioning state of the replication extension. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Replication extension model custom properties. + */ + customProperties: ReplicationExtensionModelCustomProperties; +} + +/** + * Replication extension model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/no-string-discriminator" +#suppress "@azure-tools/typespec-azure-resource-manager/no-empty-model" +@discriminator("instanceType") +model ReplicationExtensionModelCustomProperties {} + +/** + * Check name availability model. + */ +model CheckNameAvailabilityModel { + /** + * Gets or sets the resource name. + */ + name?: string; + + /** + * Gets or sets the resource type. + */ + type?: string; +} + +/** + * Check name availability response model. + */ +model CheckNameAvailabilityResponseModel { + /** + * Gets or sets a value indicating whether resource name is available or not. + */ + nameAvailable?: boolean; + + /** + * Gets or sets the reason for resource name unavailability. + */ + reason?: string; + + /** + * Gets or sets the message for resource name unavailability. + */ + message?: string; +} + +/** + * Deployment preflight model. + */ +model DeploymentPreflightModel { + /** + * Gets or sets the list of resources. + */ + @identifiers(#[]) + resources?: DeploymentPreflightResource[]; +} + +/** + * Deployment preflight resource. + */ +model DeploymentPreflightResource { + /** + * Gets or sets the resource name. + */ + name?: string; + + /** + * Gets or sets the resource type. + */ + type?: string; + + /** + * Gets or sets the location of the resource. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + location?: string; + + /** + * Gets or sets the Api version. + */ + apiVersion?: string; + + /** + * Gets or sets the properties of the resource. + */ + #suppress "@azure-tools/typespec-azure-core/no-unknown" + properties?: unknown; +} + +/** + * Defines the operation status. + */ +model OperationStatus { + /** + * Gets or sets the Id. + */ + id?: string; + + /** + * Gets or sets the operation name. + */ + name?: string; + + /** + * Gets or sets the status of the operation. ARM expects the terminal status to be one of Succeeded/ Failed/ Canceled. All other values imply that the operation is still running. + */ + status?: string; + + /** + * Gets or sets the start time. + */ + startTime?: string; + + /** + * Gets or sets the end time. + */ + endTime?: string; +} + +/** + * Vault properties. + */ +model VaultModelProperties { + /** + * Gets or sets the provisioning state of the vault. + */ + @visibility(Lifecycle.Read) + provisioningState?: ProvisioningState; + + /** + * Gets or sets the service resource Id. + */ + @visibility(Lifecycle.Read) + serviceResourceId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the type of vault. + */ + vaultType?: ReplicationVaultType; +} + +/** + * Vault model. + */ +model VaultIdentityModel { + /** + * Gets or sets the identityType which can be either SystemAssigned or None. + */ + type: VaultIdentityType; + + /** + * Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access to an Azure resource. + */ + @visibility(Lifecycle.Read) + principalId?: string; + + /** + * Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + */ + @visibility(Lifecycle.Read) + tenantId?: string; +} + +/** + * Vault model update. + */ +model VaultModelUpdate { + /** + * Gets or sets the resource tags. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" + tags?: Record; + + /** + * Vault properties. + */ + properties?: VaultModelProperties; + + /** + * Vault identity. + */ + identity?: VaultIdentityModel; + + /** + * Gets or sets the Id of the resource. + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * Gets or sets the name of the resource. + */ + @visibility(Lifecycle.Read) + name?: string; + + /** + * Gets or sets the type of the resource. + */ + @visibility(Lifecycle.Read) + type?: string; + + /** + * Metadata pertaining to creation and last modification of the resource. + */ + @visibility(Lifecycle.Read) + systemData?: SystemData; +} + +/** + * AzStackHCI cluster properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model AzStackHCIClusterProperties { + /** + * Gets or sets the AzStackHCICluster FQDN name. + */ + @minLength(1) + clusterName: string; + + /** + * Gets or sets the AzStackHCICluster resource name. + */ + @minLength(1) + resourceName: string; + + /** + * Gets or sets the Storage account name. + */ + @minLength(1) + storageAccountName: string; + + /** + * Gets or sets the list of AzStackHCICluster Storage Container. + */ + @identifiers(#[]) + storageContainers: StorageContainerProperties[]; +} + +/** + * Storage container properties. + */ +model StorageContainerProperties { + /** + * Gets or sets the Name. + */ + @minLength(1) + name: string; + + /** + * Gets or sets the ClusterSharedVolumePath. + */ + @minLength(1) + clusterSharedVolumePath: string; +} + +/** + * AzStackHCI fabric model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model AzStackHCIFabricModelCustomProperties + extends FabricModelCustomProperties { + /** + * Gets or sets the ARM Id of the AzStackHCI site. + */ + @minLength(1) + azStackHciSiteId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the Appliance name. + */ + @visibility(Lifecycle.Read) + applianceName?: string[]; + + /** + * AzStackHCI cluster properties. + */ + cluster: AzStackHCIClusterProperties; + + /** + * Gets or sets the fabric resource Id. + */ + @visibility(Lifecycle.Read) + fabricResourceId?: string; + + /** + * Gets or sets the fabric container Id. + */ + @visibility(Lifecycle.Read) + fabricContainerId?: string; + + /** + * Gets or sets the Migration solution ARM Id. + */ + @minLength(1) + migrationSolutionId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the migration hub Uri. + */ + @visibility(Lifecycle.Read) + migrationHubUri?: url; + + /** + * Gets or sets the instance type. + */ + instanceType: "AzStackHCI"; +} + +/** + * Disk controller. + */ +model DiskControllerInputs { + /** + * Gets or sets the controller name (IDE,SCSI). + */ + @minLength(1) + controllerName: string; + + /** + * Gets or sets the controller ID. + */ + controllerId: int32; + + /** + * Gets or sets the controller Location. + */ + controllerLocation: int32; +} + +/** + * Failover job model custom properties. + */ +model FailoverJobModelCustomProperties extends JobModelCustomProperties { + /** + * Gets or sets the failed over protected item details. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + protectedItemDetails?: FailoverProtectedItemProperties[]; + + /** + * Gets or sets the instance type. + */ + instanceType: "FailoverJobDetails"; +} + +/** + * Failover properties of the protected item. + */ +model FailoverProtectedItemProperties { + /** + * Gets or sets the protected item name. + */ + @visibility(Lifecycle.Read) + protectedItemName?: string; + + /** + * Gets or sets the VM name. + */ + @visibility(Lifecycle.Read) + vmName?: string; + + /** + * Gets or sets the test VM name. + */ + @visibility(Lifecycle.Read) + testVmName?: string; + + /** + * Gets or sets the recovery point Id. + */ + @visibility(Lifecycle.Read) + recoveryPointId?: string; + + /** + * Gets or sets the recovery point time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + recoveryPointTime?: utcDateTime; + + /** + * Gets or sets the network name. + */ + @visibility(Lifecycle.Read) + networkName?: string; + + /** + * Gets or sets the network subnet. + */ + @visibility(Lifecycle.Read) + subnet?: string; +} + +/** + * HyperV migrate fabric model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVMigrateFabricModelCustomProperties + extends FabricModelCustomProperties { + /** + * Gets or sets the ARM Id of the HyperV site. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" + @minLength(1) + hyperVSiteId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the fabric resource Id. + */ + @visibility(Lifecycle.Read) + fabricResourceId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the fabric container Id. + */ + @visibility(Lifecycle.Read) + fabricContainerId?: string; + + /** + * Gets or sets the migration solution ARM Id. + */ + @minLength(1) + migrationSolutionId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the migration hub Uri. + */ + @visibility(Lifecycle.Read) + migrationHubUri?: url; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVMigrate"; +} + +/** + * HyperVToAzStack disk input. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIDiskInput { + /** + * Gets or sets the disk Id. + */ + @minLength(1) + diskId: string; + + /** + * Gets or sets the target storage account ARM Id. + */ + storageContainerId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + */ + isDynamic?: boolean; + + /** + * Gets or sets the disk size in GB. + */ + diskSizeGB: int64; + + /** + * Gets or sets the type of the virtual hard disk, vhd or vhdx. + */ + @minLength(1) + diskFileFormat: string; + + /** + * Gets or sets a value indicating whether disk is os disk. + */ + isOsDisk: boolean; + + /** + * Gets or sets a value of disk block size. + */ + diskBlockSize?: int64; + + /** + * Gets or sets a value of disk logical sector size. + */ + diskLogicalSectorSize?: int64; + + /** + * Gets or sets a value of disk physical sector size. + */ + diskPhysicalSectorSize?: int64; + + /** + * Gets or sets a value of disk identifier. + */ + diskIdentifier?: string; + + /** + * Disk controller. + */ + diskController?: DiskControllerInputs; +} + +/** + * HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth and DataContract.HealthEvents.HealthEventType.AgentHealth. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIEventModelCustomProperties + extends EventModelCustomProperties { + /** + * Gets or sets the friendly name of the source which has raised this health event. + */ + @visibility(Lifecycle.Read) + eventSourceFriendlyName?: string; + + /** + * Gets or sets the protected item friendly name. + */ + @visibility(Lifecycle.Read) + protectedItemFriendlyName?: string; + + /** + * Gets or sets the source appliance name. + */ + @visibility(Lifecycle.Read) + sourceApplianceName?: string; + + /** + * Gets or sets the source target name. + */ + @visibility(Lifecycle.Read) + targetApplianceName?: string; + + /** + * Gets or sets the server type. + */ + @visibility(Lifecycle.Read) + serverType?: string; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; +} + +/** + * HyperVToAzStackHCI NIC properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCINicInput { + /** + * Gets or sets the NIC Id. + */ + @minLength(1) + nicId: string; + + /** + * Gets or sets the network name. + */ + @visibility(Lifecycle.Read) + networkName?: string; + + /** + * Gets or sets the target network Id within AzStackHCI Cluster. + */ + targetNetworkId?: string; + + /** + * Gets or sets the target test network Id within AzStackHCI Cluster. + */ + testNetworkId?: string; + + /** + * Gets or sets the selection type of the NIC. + */ + selectionTypeForFailover: VMNicSelection; + + /** + * Gets or sets a value indicating whether static ip migration is enabled. + */ + isStaticIpMigrationEnabled?: boolean; + + /** + * Gets or sets a value indicating whether mac address migration is enabled. + */ + isMacMigrationEnabled?: boolean; +} + +/** + * HyperV to AzStackHCI planned failover model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIPlannedFailoverModelCustomProperties + extends PlannedFailoverModelCustomProperties { + /** + * Gets or sets a value indicating whether VM needs to be shut down. + */ + shutdownSourceVM: boolean; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; +} + +/** + * HyperV To AzStackHCI Policy model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIPolicyModelCustomProperties + extends PolicyModelCustomProperties { + /** + * Gets or sets the duration in minutes until which the recovery points need to be stored. + */ + recoveryPointHistoryInMinutes: int32; + + /** + * Gets or sets the crash consistent snapshot frequency (in minutes). + */ + crashConsistentFrequencyInMinutes: int32; + + /** + * Gets or sets the app consistent snapshot frequency (in minutes). + */ + appConsistentFrequencyInMinutes: int32; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; +} + +/** + * HyperVToAzStackHCI protected disk properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIProtectedDiskProperties { + /** + * Gets or sets the ARM Id of the storage container. + */ + @visibility(Lifecycle.Read) + storageContainerId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the local path of the storage container. + */ + @visibility(Lifecycle.Read) + storageContainerLocalPath?: string; + + /** + * Gets or sets the source disk Id. + */ + @visibility(Lifecycle.Read) + sourceDiskId?: string; + + /** + * Gets or sets the source disk Name. + */ + @visibility(Lifecycle.Read) + sourceDiskName?: string; + + /** + * Gets or sets the seed disk name. + */ + @visibility(Lifecycle.Read) + seedDiskName?: string; + + /** + * Gets or sets the test failover clone disk. + */ + @visibility(Lifecycle.Read) + testMigrateDiskName?: string; + + /** + * Gets or sets the failover clone disk. + */ + @visibility(Lifecycle.Read) + migrateDiskName?: string; + + /** + * Gets or sets a value indicating whether the disk is the OS disk. + */ + @visibility(Lifecycle.Read) + isOsDisk?: boolean; + + /** + * Gets or sets the disk capacity in bytes. + */ + @visibility(Lifecycle.Read) + capacityInBytes?: int64; + + /** + * Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + */ + @visibility(Lifecycle.Read) + isDynamic?: boolean; + + /** + * Gets or sets the disk type. + */ + @visibility(Lifecycle.Read) + diskType?: string; + + /** + * Gets or sets a value of disk block size. + */ + @visibility(Lifecycle.Read) + diskBlockSize?: int64; + + /** + * Gets or sets a value of disk logical sector size. + */ + @visibility(Lifecycle.Read) + diskLogicalSectorSize?: int64; + + /** + * Gets or sets a value of disk physical sector size. + */ + @visibility(Lifecycle.Read) + diskPhysicalSectorSize?: int64; +} + +/** + * HyperV to AzStackHCI Protected item model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIProtectedItemModelCustomProperties + extends ProtectedItemModelCustomProperties { + /** + * Gets or sets the location of the protected item. + */ + @visibility(Lifecycle.Read) + activeLocation?: ProtectedItemActiveLocation; + + /** + * Gets or sets the Target HCI Cluster ARM Id. + */ + @minLength(1) + targetHciClusterId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the Target Arc Cluster Custom Location ARM Id. + */ + @minLength(1) + targetArcClusterCustomLocationId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the Target AzStackHCI cluster name. + */ + @visibility(Lifecycle.Read) + targetAzStackHciClusterName?: string; + + /** + * Gets or sets the ARM Id of the discovered machine. + */ + @minLength(1) + fabricDiscoveryMachineId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the list of disks to replicate. + */ + @identifiers(#[]) + disksToInclude: HyperVToAzStackHCIDiskInput[]; + + /** + * Gets or sets the list of VM NIC to replicate. + */ + @identifiers(#[]) + nicsToInclude: HyperVToAzStackHCINicInput[]; + + /** + * Gets or sets the source VM display name. + */ + @visibility(Lifecycle.Read) + sourceVmName?: string; + + /** + * Gets or sets the source VM CPU cores. + */ + @visibility(Lifecycle.Read) + sourceCpuCores?: int32; + + /** + * Gets or sets the source VM ram memory size in megabytes. + */ + @visibility(Lifecycle.Read) + sourceMemoryInMegaBytes?: float64; + + /** + * Gets or sets the target VM display name. + */ + targetVmName?: string; + + /** + * Gets or sets the target resource group ARM Id. + */ + @minLength(1) + targetResourceGroupId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the target storage container ARM Id. + */ + @minLength(1) + storageContainerId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the hypervisor generation of the virtual machine. + */ + @minLength(1) + hyperVGeneration: string; + + /** + * Gets or sets the target network Id within AzStackHCI Cluster. + */ + targetNetworkId?: string; + + /** + * Gets or sets the target test network Id within AzStackHCI Cluster. + */ + testNetworkId?: string; + + /** + * Gets or sets the target CPU cores. + */ + targetCpuCores?: int32; + + /** + * Gets or sets a value indicating whether memory is dynamical. + */ + isDynamicRam?: boolean; + + /** + * Protected item dynamic memory config. + */ + dynamicMemoryConfig?: ProtectedItemDynamicMemoryConfig; + + /** + * Gets or sets the target memory in mega-bytes. + */ + targetMemoryInMegaBytes?: int32; + + /** + * Gets or sets the Run As account Id. + */ + @minLength(1) + runAsAccountId: string; + + /** + * Gets or sets the source fabric agent name. + */ + @minLength(1) + sourceFabricAgentName: string; + + /** + * Gets or sets the target fabric agent name. + */ + @minLength(1) + targetFabricAgentName: string; + + /** + * Gets or sets the source appliance name. + */ + @visibility(Lifecycle.Read) + sourceApplianceName?: string; + + /** + * Gets or sets the target appliance name. + */ + @visibility(Lifecycle.Read) + targetApplianceName?: string; + + /** + * Gets or sets the type of the OS. + */ + @visibility(Lifecycle.Read) + osType?: string; + + /** + * Gets or sets the name of the OS. + */ + @visibility(Lifecycle.Read) + osName?: string; + + /** + * Gets or sets the firmware type. + */ + @visibility(Lifecycle.Read) + firmwareType?: string; + + /** + * Gets or sets the target location. + */ + @visibility(Lifecycle.Read) + targetLocation?: string; + + /** + * Gets or sets the location of Azure Arc HCI custom location resource. + */ + @minLength(1) + customLocationRegion: string; + + /** + * Gets or sets the recovery point Id to which the VM was failed over. + */ + @visibility(Lifecycle.Read) + failoverRecoveryPointId?: string; + + /** + * Gets or sets the last recovery point received time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastRecoveryPointReceived?: utcDateTime; + + /** + * Gets or sets the last recovery point Id. + */ + @visibility(Lifecycle.Read) + lastRecoveryPointId?: string; + + /** + * Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks in the source VM. + */ + @visibility(Lifecycle.Read) + initialReplicationProgressPercentage?: int32; + + /** + * Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source VM. + */ + @visibility(Lifecycle.Read) + resyncProgressPercentage?: int32; + + /** + * Gets or sets the list of protected disks. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + protectedDisks?: HyperVToAzStackHCIProtectedDiskProperties[]; + + /** + * Gets or sets the VM NIC details. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + protectedNics?: HyperVToAzStackHCIProtectedNicProperties[]; + + /** + * Gets or sets the BIOS Id of the target AzStackHCI VM. + */ + @visibility(Lifecycle.Read) + targetVmBiosId?: string; + + /** + * Gets or sets the latest timestamp that replication status is updated. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastReplicationUpdateTime?: utcDateTime; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; +} + +/** + * Protected item dynamic memory config. + */ +model ProtectedItemDynamicMemoryConfig { + /** + * Gets or sets maximum memory in MB. + */ + maximumMemoryInMegaBytes: int64; + + /** + * Gets or sets minimum memory in MB. + */ + minimumMemoryInMegaBytes: int64; + + /** + * Gets or sets target memory buffer in %. + */ + targetMemoryBufferPercentage: int32; +} + +/** + * HyperVToAzStackHCI NIC properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIProtectedNicProperties { + /** + * Gets or sets the NIC Id. + */ + @visibility(Lifecycle.Read) + nicId?: string; + + /** + * Gets or sets the NIC mac address. + */ + @visibility(Lifecycle.Read) + macAddress?: string; + + /** + * Gets or sets the network name. + */ + @visibility(Lifecycle.Read) + networkName?: string; + + /** + * Gets or sets the target network Id within AzStackHCI Cluster. + */ + @visibility(Lifecycle.Read) + targetNetworkId?: string; + + /** + * Gets or sets the target test network Id within AzStackHCI Cluster. + */ + @visibility(Lifecycle.Read) + testNetworkId?: string; + + /** + * Gets or sets the selection type of the NIC. + */ + @visibility(Lifecycle.Read) + selectionTypeForFailover?: VMNicSelection; +} + +/** + * HyperV to AzStackHCI Protected item model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIProtectedItemModelCustomPropertiesUpdate + extends ProtectedItemModelCustomPropertiesUpdate { + /** + * Gets or sets the list of VM NIC to replicate. + */ + @identifiers(#[]) + nicsToInclude?: HyperVToAzStackHCINicInput[]; + + /** + * Gets or sets the target CPU cores. + */ + targetCpuCores?: int32; + + /** + * Gets or sets a value indicating whether memory is dynamical. + */ + isDynamicRam?: boolean; + + /** + * Protected item dynamic memory config. + */ + dynamicMemoryConfig?: ProtectedItemDynamicMemoryConfig; + + /** + * Gets or sets the target memory in mega-bytes. + */ + targetMemoryInMegaBytes?: int32; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; + + /** + * Gets or sets the type of the OS. + */ + osType?: string; +} + +/** + * HyperV to AzStackHCI recovery point model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIRecoveryPointModelCustomProperties + extends RecoveryPointModelCustomProperties { + /** + * Gets or sets the list of the disk Ids. + */ + @visibility(Lifecycle.Read) + diskIds?: string[]; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; +} + +/** + * HyperV to AzStackHCI Replication extension model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model HyperVToAzStackHCIReplicationExtensionModelCustomProperties + extends ReplicationExtensionModelCustomProperties { + /** + * Gets or sets the ARM Id of the source HyperV fabric. + */ + @minLength(1) + hyperVFabricArmId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the HyperV site. + */ + @visibility(Lifecycle.Read) + hyperVSiteId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the target AzStackHCI fabric. + */ + @minLength(1) + azStackHciFabricArmId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the AzStackHCI site. + */ + @visibility(Lifecycle.Read) + azStackHciSiteId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the storage account Id. + */ + storageAccountId?: string; + + /** + * Gets or sets the Sas Secret of storage account. + */ + storageAccountSasSecretName?: string; + + /** + * Gets or sets the Uri of ASR. + */ + @visibility(Lifecycle.Read) + asrServiceUri?: url; + + /** + * Gets or sets the Uri of Rcm. + */ + @visibility(Lifecycle.Read) + rcmServiceUri?: url; + + /** + * Gets or sets the Uri of Gateway. + */ + @visibility(Lifecycle.Read) + gatewayServiceUri?: url; + + /** + * Gets or sets the gateway service Id of source. + */ + @visibility(Lifecycle.Read) + sourceGatewayServiceId?: string; + + /** + * Gets or sets the gateway service Id of target. + */ + @visibility(Lifecycle.Read) + targetGatewayServiceId?: string; + + /** + * Gets or sets the source storage container name. + */ + @visibility(Lifecycle.Read) + sourceStorageContainerName?: string; + + /** + * Gets or sets the target storage container name. + */ + @visibility(Lifecycle.Read) + targetStorageContainerName?: string; + + /** + * Gets or sets the resource location. + */ + @visibility(Lifecycle.Read) + resourceLocation?: string; + + /** + * Gets or sets the subscription. + */ + @visibility(Lifecycle.Read) + subscriptionId?: string; + + /** + * Gets or sets the resource group. + */ + @visibility(Lifecycle.Read) + resourceGroup?: string; + + /** + * Gets or sets the instance type. + */ + instanceType: "HyperVToAzStackHCI"; +} + +/** + * Operation model. + */ +model OperationModel { + /** + * Gets or sets the name of the operation. + */ + name?: string; + + /** + * Gets or sets a value indicating whether the action is specific to data plane or control plane. + */ + isDataAction?: boolean; + + /** + * Gets or sets the executor of the operation. + */ + origin?: string; + + /** + * Operation model properties. + */ + display?: OperationModelProperties; +} + +/** + * Operation model properties. + */ +model OperationModelProperties { + /** + * Gets or sets the resource provider name. + */ + provider?: string; + + /** + * Gets or sets resource name. + */ + resource?: string; + + /** + * Gets or sets the operation. + */ + operation?: string; + + /** + * Gets or sets the description. + */ + description?: string; +} + +/** + * Available operations of the service. + */ +model OperationModelCollection { + /** + * Gets or sets the list of operations. + */ + @identifiers(#[]) + value?: OperationModel[]; + + /** + * Gets or sets the value of next link. + */ + nextLink?: string; +} + +/** + * System data required to be defined for Azure resources. + */ +model SystemDataModel { + /** + * Gets or sets identity that created the resource. + */ + createdBy?: string; + + /** + * Gets or sets the type of identity that created the resource: user, application,managedIdentity. + */ + createdByType?: string; + + /** + * Gets or sets the timestamp of resource creation (UTC). + */ + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + createdAt?: utcDateTime; + + /** + * Gets or sets the identity that last modified the resource. + */ + lastModifiedBy?: string; + + /** + * Gets or sets the type of identity that last modified the resource: user, application,managedIdentity. + */ + lastModifiedByType?: string; + + /** + * Gets or sets the timestamp of resource last modification (UTC). + */ + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastModifiedAt?: utcDateTime; +} + +/** + * Test failover cleanup job model custom properties. + */ +model TestFailoverCleanupJobModelCustomProperties + extends JobModelCustomProperties { + /** + * Gets or sets the test failover cleanup comments. + */ + @visibility(Lifecycle.Read) + comments?: string; + + /** + * Gets or sets the instance type. + */ + instanceType: "TestFailoverCleanupJobDetails"; +} + +/** + * Test failover job model custom properties. + */ +model TestFailoverJobModelCustomProperties extends JobModelCustomProperties { + /** + * Gets or sets the test VM details. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + protectedItemDetails?: FailoverProtectedItemProperties[]; + + /** + * Gets or sets the instance type. + */ + instanceType: "TestFailoverJobDetails"; +} + +/** + * VMware fabric agent model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareFabricAgentModelCustomProperties + extends FabricAgentModelCustomProperties { + /** + * Gets or sets the BIOS Id of the fabric agent machine. + */ + @minLength(1) + biosId: string; + + /** + * Identity model. + */ + marsAuthenticationIdentity: IdentityModel; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMware"; +} + +/** + * VMware migrate fabric model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareMigrateFabricModelCustomProperties + extends FabricModelCustomProperties { + /** + * Gets or sets the ARM Id of the VMware site. + */ + @minLength(1) + vmwareSiteId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the migration solution. + */ + @minLength(1) + migrationSolutionId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareMigrate"; +} + +/** + * VMwareToAzStack disk input. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIDiskInput { + /** + * Gets or sets the disk Id. + */ + @minLength(1) + diskId: string; + + /** + * Gets or sets the target storage account ARM Id. + */ + storageContainerId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + */ + isDynamic?: boolean; + + /** + * Gets or sets the disk size in GB. + */ + diskSizeGB: int64; + + /** + * Gets or sets the type of the virtual hard disk, vhd or vhdx. + */ + @minLength(1) + diskFileFormat: string; + + /** + * Gets or sets a value indicating whether disk is os disk. + */ + isOsDisk: boolean; + + /** + * Gets or sets a value of disk block size. + */ + diskBlockSize?: int64; + + /** + * Gets or sets a value of disk logical sector size. + */ + diskLogicalSectorSize?: int64; + + /** + * Gets or sets a value of disk physical sector size. + */ + diskPhysicalSectorSize?: int64; + + /** + * Gets or sets a value of disk identifier. + */ + diskIdentifier?: string; + + /** + * Disk controller. + */ + diskController?: DiskControllerInputs; +} + +/** + * VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth and DataContract.HealthEvents.HealthEventType.AgentHealth. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIEventModelCustomProperties + extends EventModelCustomProperties { + /** + * Gets or sets the friendly name of the source which has raised this health event. + */ + @visibility(Lifecycle.Read) + eventSourceFriendlyName?: string; + + /** + * Gets or sets the protected item friendly name. + */ + @visibility(Lifecycle.Read) + protectedItemFriendlyName?: string; + + /** + * Gets or sets the source appliance name. + */ + @visibility(Lifecycle.Read) + sourceApplianceName?: string; + + /** + * Gets or sets the source target name. + */ + @visibility(Lifecycle.Read) + targetApplianceName?: string; + + /** + * Gets or sets the server type. + */ + @visibility(Lifecycle.Read) + serverType?: string; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCI"; +} + +/** + * VMwareToAzStackHCI NIC properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCINicInput { + /** + * Gets or sets the NIC Id. + */ + @minLength(1) + nicId: string; + + /** + * Gets or sets the NIC label. + */ + @minLength(1) + label: string; + + /** + * Gets or sets the network name. + */ + @visibility(Lifecycle.Read) + networkName?: string; + + /** + * Gets or sets the target network Id within AzStackHCI Cluster. + */ + targetNetworkId?: string; + + /** + * Gets or sets the target test network Id within AzStackHCI Cluster. + */ + testNetworkId?: string; + + /** + * Gets or sets the selection type of the NIC. + */ + selectionTypeForFailover: VMNicSelection; + + /** + * Gets or sets a value indicating whether static ip migration is enabled. + */ + isStaticIpMigrationEnabled?: boolean; + + /** + * Gets or sets a value indicating whether mac address migration is enabled. + */ + isMacMigrationEnabled?: boolean; +} + +/** + * VMware to AzStackHCI planned failover model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIPlannedFailoverModelCustomProperties + extends PlannedFailoverModelCustomProperties { + /** + * Gets or sets a value indicating whether VM needs to be shut down. + */ + shutdownSourceVM: boolean; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCI"; +} + +/** + * VMware To AzStackHCI Policy model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIPolicyModelCustomProperties + extends PolicyModelCustomProperties { + /** + * Gets or sets the duration in minutes until which the recovery points need to be stored. + */ + recoveryPointHistoryInMinutes: int32; + + /** + * Gets or sets the crash consistent snapshot frequency (in minutes). + */ + crashConsistentFrequencyInMinutes: int32; + + /** + * Gets or sets the app consistent snapshot frequency (in minutes). + */ + appConsistentFrequencyInMinutes: int32; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCI"; +} + +/** + * VMwareToAzStackHCI protected disk properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIProtectedDiskProperties { + /** + * Gets or sets the ARM Id of the storage container. + */ + @visibility(Lifecycle.Read) + storageContainerId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the local path of the storage container. + */ + @visibility(Lifecycle.Read) + storageContainerLocalPath?: string; + + /** + * Gets or sets the source disk Id. + */ + @visibility(Lifecycle.Read) + sourceDiskId?: string; + + /** + * Gets or sets the source disk Name. + */ + @visibility(Lifecycle.Read) + sourceDiskName?: string; + + /** + * Gets or sets the seed disk name. + */ + @visibility(Lifecycle.Read) + seedDiskName?: string; + + /** + * Gets or sets the test failover clone disk. + */ + @visibility(Lifecycle.Read) + testMigrateDiskName?: string; + + /** + * Gets or sets the failover clone disk. + */ + @visibility(Lifecycle.Read) + migrateDiskName?: string; + + /** + * Gets or sets a value indicating whether the disk is the OS disk. + */ + @visibility(Lifecycle.Read) + isOsDisk?: boolean; + + /** + * Gets or sets the disk capacity in bytes. + */ + @visibility(Lifecycle.Read) + capacityInBytes?: int64; + + /** + * Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + */ + @visibility(Lifecycle.Read) + isDynamic?: boolean; + + /** + * Gets or sets the disk type. + */ + @visibility(Lifecycle.Read) + diskType?: string; + + /** + * Gets or sets a value of disk block size. + */ + @visibility(Lifecycle.Read) + diskBlockSize?: int64; + + /** + * Gets or sets a value of disk logical sector size. + */ + @visibility(Lifecycle.Read) + diskLogicalSectorSize?: int64; + + /** + * Gets or sets a value of disk physical sector size. + */ + @visibility(Lifecycle.Read) + diskPhysicalSectorSize?: int64; +} + +/** + * VMware to AzStackHCI Protected item model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIProtectedItemModelCustomProperties + extends ProtectedItemModelCustomProperties { + /** + * Gets or sets the location of the protected item. + */ + @visibility(Lifecycle.Read) + activeLocation?: ProtectedItemActiveLocation; + + /** + * Gets or sets the Target HCI Cluster ARM Id. + */ + @minLength(1) + targetHciClusterId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the Target Arc Cluster Custom Location ARM Id. + */ + @minLength(1) + targetArcClusterCustomLocationId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the Target AzStackHCI cluster name. + */ + @visibility(Lifecycle.Read) + targetAzStackHciClusterName?: string; + + /** + * Gets or sets the target storage container ARM Id. + */ + @minLength(1) + storageContainerId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the target resource group ARM Id. + */ + @minLength(1) + targetResourceGroupId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the target location. + */ + @visibility(Lifecycle.Read) + targetLocation?: string; + + /** + * Gets or sets the location of Azure Arc HCI custom location resource. + */ + @minLength(1) + customLocationRegion: string; + + /** + * Gets or sets the list of disks to replicate. + */ + @identifiers(#[]) + disksToInclude: VMwareToAzStackHCIDiskInput[]; + + /** + * Gets or sets the list of VM NIC to replicate. + */ + @identifiers(#[]) + nicsToInclude: VMwareToAzStackHCINicInput[]; + + /** + * Gets or sets the list of protected disks. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + protectedDisks?: VMwareToAzStackHCIProtectedDiskProperties[]; + + /** + * Gets or sets the VM NIC details. + */ + @visibility(Lifecycle.Read) + @identifiers(#[]) + protectedNics?: VMwareToAzStackHCIProtectedNicProperties[]; + + /** + * Gets or sets the BIOS Id of the target AzStackHCI VM. + */ + @visibility(Lifecycle.Read) + targetVmBiosId?: string; + + /** + * Gets or sets the target VM display name. + */ + targetVmName?: string; + + /** + * Gets or sets the hypervisor generation of the virtual machine possible values are 1,2. + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" + @minLength(1) + hyperVGeneration: string; + + /** + * Gets or sets the target network Id within AzStackHCI Cluster. + */ + targetNetworkId?: string; + + /** + * Gets or sets the target test network Id within AzStackHCI Cluster. + */ + testNetworkId?: string; + + /** + * Gets or sets the target CPU cores. + */ + targetCpuCores?: int32; + + /** + * Gets or sets a value indicating whether memory is dynamical. + */ + isDynamicRam?: boolean; + + /** + * Protected item dynamic memory config. + */ + dynamicMemoryConfig?: ProtectedItemDynamicMemoryConfig; + + /** + * Gets or sets the target memory in mega-bytes. + */ + targetMemoryInMegaBytes?: int32; + + /** + * Gets or sets the type of the OS. + */ + @visibility(Lifecycle.Read) + osType?: string; + + /** + * Gets or sets the name of the OS. + */ + @visibility(Lifecycle.Read) + osName?: string; + + /** + * Gets or sets the firmware type. + */ + @visibility(Lifecycle.Read) + firmwareType?: string; + + /** + * Gets or sets the ARM Id of the discovered machine. + */ + @minLength(1) + fabricDiscoveryMachineId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the source VM display name. + */ + @visibility(Lifecycle.Read) + sourceVmName?: string; + + /** + * Gets or sets the source VM CPU cores. + */ + @visibility(Lifecycle.Read) + sourceCpuCores?: int32; + + /** + * Gets or sets the source VM ram memory size in megabytes. + */ + @visibility(Lifecycle.Read) + sourceMemoryInMegaBytes?: float64; + + /** + * Gets or sets the run as account Id. + */ + @minLength(1) + runAsAccountId: string; + + /** + * Gets or sets the source fabric agent name. + */ + @minLength(1) + sourceFabricAgentName: string; + + /** + * Gets or sets the target fabric agent name. + */ + @minLength(1) + targetFabricAgentName: string; + + /** + * Gets or sets the source appliance name. + */ + @visibility(Lifecycle.Read) + sourceApplianceName?: string; + + /** + * Gets or sets the target appliance name. + */ + @visibility(Lifecycle.Read) + targetApplianceName?: string; + + /** + * Gets or sets the recovery point Id to which the VM was failed over. + */ + @visibility(Lifecycle.Read) + failoverRecoveryPointId?: string; + + /** + * Gets or sets the last recovery point received time. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastRecoveryPointReceived?: utcDateTime; + + /** + * Gets or sets the last recovery point Id. + */ + @visibility(Lifecycle.Read) + lastRecoveryPointId?: string; + + /** + * Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks in the source VM. + */ + @visibility(Lifecycle.Read) + initialReplicationProgressPercentage?: int32; + + /** + * Gets or sets the migration progress percentage. + */ + @visibility(Lifecycle.Read) + migrationProgressPercentage?: int32; + + /** + * Gets or sets the resume progress percentage. + */ + @visibility(Lifecycle.Read) + resumeProgressPercentage?: int32; + + /** + * Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source VM. + */ + @visibility(Lifecycle.Read) + resyncProgressPercentage?: int32; + + /** + * Gets or sets the resync retry count. + */ + @visibility(Lifecycle.Read) + resyncRetryCount?: int64; + + /** + * Gets or sets a value indicating whether resync is required. + */ + @visibility(Lifecycle.Read) + resyncRequired?: boolean; + + /** + * Gets or sets the resync state. + */ + @visibility(Lifecycle.Read) + resyncState?: VMwareToAzureMigrateResyncState; + + /** + * Gets or sets a value indicating whether auto resync is to be done. + */ + performAutoResync?: boolean; + + /** + * Gets or sets the resume retry count. + */ + @visibility(Lifecycle.Read) + resumeRetryCount?: int64; + + /** + * Gets or sets the latest timestamp that replication status is updated. + */ + @visibility(Lifecycle.Read) + // FIXME: (utcDateTime) Please double check that this is the correct type for your scenario. + lastReplicationUpdateTime?: utcDateTime; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCI"; +} + +/** + * VMwareToAzStackHCI NIC properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIProtectedNicProperties { + /** + * Gets or sets the NIC Id. + */ + @visibility(Lifecycle.Read) + nicId?: string; + + /** + * Gets or sets the NIC mac address. + */ + @visibility(Lifecycle.Read) + macAddress?: string; + + /** + * Gets or sets the NIC label. + */ + @visibility(Lifecycle.Read) + label?: string; + + /** + * Gets or sets a value indicating whether this is the primary NIC. + */ + isPrimaryNic?: boolean; + + /** + * Gets or sets the network name. + */ + @visibility(Lifecycle.Read) + networkName?: string; + + /** + * Gets or sets the target network Id within AzStackHCI Cluster. + */ + @visibility(Lifecycle.Read) + targetNetworkId?: string; + + /** + * Gets or sets the target test network Id within AzStackHCI Cluster. + */ + @visibility(Lifecycle.Read) + testNetworkId?: string; + + /** + * Gets or sets the selection type of the NIC. + */ + @visibility(Lifecycle.Read) + selectionTypeForFailover?: VMNicSelection; +} + +/** + * VMware to AzStackHCI Protected item model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIProtectedItemModelCustomPropertiesUpdate + extends ProtectedItemModelCustomPropertiesUpdate { + /** + * Gets or sets the list of VM NIC to replicate. + */ + @identifiers(#[]) + nicsToInclude?: VMwareToAzStackHCINicInput[]; + + /** + * Gets or sets the target CPU cores. + */ + targetCpuCores?: int32; + + /** + * Gets or sets a value indicating whether memory is dynamical. + */ + isDynamicRam?: boolean; + + /** + * Protected item dynamic memory config. + */ + dynamicMemoryConfig?: ProtectedItemDynamicMemoryConfig; + + /** + * Gets or sets the target memory in mega-bytes. + */ + targetMemoryInMegaBytes?: int32; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCI"; + + /** + * Gets or sets the type of the OS. + */ + osType?: string; +} + +/** + * VMware to AzStackHCI recovery point model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIRecoveryPointModelCustomProperties + extends RecoveryPointModelCustomProperties { + /** + * Gets or sets the list of the disk Ids. + */ + @visibility(Lifecycle.Read) + diskIds?: string[]; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCIRecoveryPointModelCustomProperties"; +} + +/** + * VMware to AzStackHCI Replication extension model custom properties. + */ +#suppress "@azure-tools/typespec-azure-core/casing-style" +model VMwareToAzStackHCIReplicationExtensionModelCustomProperties + extends ReplicationExtensionModelCustomProperties { + /** + * Gets or sets the ARM Id of the source VMware fabric. + */ + @minLength(1) + vmwareFabricArmId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the VMware site. + */ + @visibility(Lifecycle.Read) + vmwareSiteId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the target AzStackHCI fabric. + */ + @minLength(1) + azStackHciFabricArmId: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the ARM Id of the AzStackHCI site. + */ + @visibility(Lifecycle.Read) + azStackHciSiteId?: Azure.Core.armResourceIdentifier; + + /** + * Gets or sets the storage account Id. + */ + storageAccountId?: string; + + /** + * Gets or sets the Sas Secret of storage account. + */ + storageAccountSasSecretName?: string; + + /** + * Gets or sets the Uri of ASR. + */ + @visibility(Lifecycle.Read) + asrServiceUri?: url; + + /** + * Gets or sets the Uri of Rcm. + */ + @visibility(Lifecycle.Read) + rcmServiceUri?: url; + + /** + * Gets or sets the Uri of Gateway. + */ + @visibility(Lifecycle.Read) + gatewayServiceUri?: url; + + /** + * Gets or sets the gateway service Id of source. + */ + @visibility(Lifecycle.Read) + sourceGatewayServiceId?: string; + + /** + * Gets or sets the gateway service Id of target. + */ + @visibility(Lifecycle.Read) + targetGatewayServiceId?: string; + + /** + * Gets or sets the source storage container name. + */ + @visibility(Lifecycle.Read) + sourceStorageContainerName?: string; + + /** + * Gets or sets the target storage container name. + */ + @visibility(Lifecycle.Read) + targetStorageContainerName?: string; + + /** + * Gets or sets the resource location. + */ + @visibility(Lifecycle.Read) + resourceLocation?: string; + + /** + * Gets or sets the subscription. + */ + @visibility(Lifecycle.Read) + subscriptionId?: string; + + /** + * Gets or sets the resource group. + */ + @visibility(Lifecycle.Read) + resourceGroup?: string; + + /** + * Gets or sets the instance type. + */ + instanceType: "VMwareToAzStackHCI"; +} diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/routes.tsp b/tests-upgrade/tests-emitter/DataReplication.Management.brown/routes.tsp new file mode 100644 index 00000000000..4155ae46303 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/routes.tsp @@ -0,0 +1,97 @@ +// FIXME: Operations in this file are not detected as a resource operation, please confirm the conversion result manually + +import "@azure-tools/typespec-azure-core"; +import "@typespec/rest"; +import "./models.tsp"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using Azure.ResourceManager; + +namespace Microsoft.DataReplication; + +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-interface-requires-decorator" "Cannot use @armResourceOperations decorator here, the auto-generated routes do not match feature requirements" +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-operation" "Cannot use @armResourceOperations decorator here, the auto-generated routes do not match feature requirements" +interface CheckNameAvailability { + /** + * Checks the resource name availability. + */ + @summary("Performs the resource name availability check.") + @route("/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability") + @post + post( + ...ApiVersionParameter, + ...SubscriptionIdParameter, + ...LocationResourceParameter, + + /** + * Resource details. + */ + @body + body?: CheckNameAvailabilityModel, + ): ArmResponse | ErrorResponse; +} + +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-interface-requires-decorator" "Cannot use @armResourceOperations decorator here, the auto-generated routes do not match feature requirements" +interface DeploymentPreflight { + /** + * Performs resource deployment preflight validation. + */ + @summary("Performs resource deployment validation.") + @route("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight") + @armResourceAction(DeploymentPreflightModel) + @post + post( + ...ApiVersionParameter, + ...SubscriptionIdParameter, + ...ResourceGroupParameter, + + /** + * Deployment Id. + */ + @path + deploymentId: string, + + /** + * Deployment preflight model. + */ + @body + body?: DeploymentPreflightModel, + ): ArmResponse | ErrorResponse; +} + +@armResourceOperations +interface OperationResults { + /** + * Gets the operations. + */ + @summary("Gets the operation result status.") + @route("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/operationResults/{operationId}") + @armResourceRead(ArmResponse) + @get + get( + ...ApiVersionParameter, + ...SubscriptionIdParameter, + ...ResourceGroupParameter, + ...Foundations.OperationIdParameter, + ): ArmResponse | ErrorResponse; +} + +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-interface-requires-decorator" "Cannot use @armResourceOperations decorator here, the auto-generated routes do not match feature requirements" +interface LocationBasedOperationResults { + /** + * Gets the location based operation result. + */ + @summary("Gets the location based operation result status.") + @route("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}") + @armResourceRead(ArmResponse) + @get + get( + ...ApiVersionParameter, + ...SubscriptionIdParameter, + ...ResourceGroupParameter, + ...LocationResourceParameter, + ...Foundations.OperationIdParameter, + ): ArmResponse | ErrorResponse; +} diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/.gitattributes b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.csproj b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.csproj new file mode 100644 index 00000000000..9f3a2ada04f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.RecoveryServicesDataReplication.private + false + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication + true + false + ./bin + $(OutputPath) + Az.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.nuspec b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.nuspec new file mode 100644 index 00000000000..3b6bb66b92a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.nuspec @@ -0,0 +1,32 @@ + + + + Az.RecoveryServicesDataReplication + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: RecoveryServicesDataReplication cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule RecoveryServicesDataReplication + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.psm1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.psm1 new file mode 100644 index 00000000000..dc0a7d5834a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Az.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Properties/AssemblyInfo.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..1187819d16b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// 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. + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: System.Reflection.AssemblyCompanyAttribute("Microsoft")] +[assembly: System.Reflection.AssemblyCopyrightAttribute("Copyright © Microsoft")] +[assembly: System.Reflection.AssemblyProductAttribute("Microsoft Azure PowerShell")] +[assembly: System.Reflection.AssemblyTitleAttribute("Microsoft Azure PowerShell - AzureSiteRecoveryManagementServiceApi")] +[assembly: System.Reflection.AssemblyFileVersionAttribute("0.1.0.0")] +[assembly: System.Reflection.AssemblyVersionAttribute("0.1.0.0")] +[assembly: System.Runtime.InteropServices.ComVisibleAttribute(false)] +[assembly: System.CLSCompliantAttribute(false)] \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/README.md new file mode 100644 index 00000000000..1ad7f320548 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/README.md @@ -0,0 +1,24 @@ + +# Az.RecoveryServicesDataReplication +This directory contains the PowerShell module for the RecoveryServicesDataReplication 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.RecoveryServicesDataReplication`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/build-module.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/build-module.ps1 new file mode 100644 index 00000000000..4f6389e8381 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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 -Force -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 -Force -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 -Force +} +$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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $internalFolder + +$psd1 = Join-Path $PSScriptRoot './Az.RecoveryServicesDataReplication.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.RecoveryServicesDataReplication' +$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: RecoveryServicesDataReplication cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue -Force + } + $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.RecoveryServicesDataReplication.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 '../../../tools/BuildScripts/AdaptAutorestModule.ps1' + $afterBuildTasksArgs = ConvertFrom-Json '{"SubModuleName":"Az.RecoveryServicesDataReplication","ModuleRootName":"$(root-module-name)"}' -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/DataReplication.Management.brown/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..cb4c10b65dc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/create-model-cmdlets.ps1 @@ -0,0 +1,263 @@ +# ---------------------------------------------------------------------------------- +# 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.RecoveryServicesDataReplication' + } + $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}" + $Prefix = 'Az' + # remove duplicated module name + if ($ObjectType.StartsWith('RecoveryServicesDataReplication')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'RecoveryServicesDataReplication' + } + $OutputPath = Join-Path -ChildPath "New-${Prefix}${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] + 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-${Prefix}${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} { + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ModelCmdletAttribute()] + [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/DataReplication.Management.brown/target/custom/Az.RecoveryServicesDataReplication.custom.psm1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/custom/Az.RecoveryServicesDataReplication.custom.psm1 new file mode 100644 index 00000000000..1f15a82da10 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/custom/Az.RecoveryServicesDataReplication.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.RecoveryServicesDataReplication.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/custom/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/custom/README.md new file mode 100644 index 00000000000..ac65a2a2e9d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.RecoveryServicesDataReplication` 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.RecoveryServicesDataReplication.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.RecoveryServicesDataReplication` 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication`. 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.RecoveryServicesDataReplication`. +- `Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.RecoveryServicesDataReplication`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/docs/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/docs/README.md new file mode 100644 index 00000000000..c733ecf8e14 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.RecoveryServicesDataReplication` 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.RecoveryServicesDataReplication` 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/DataReplication.Management.brown/target/examples/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/export-surface.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/export-surface.ps1 new file mode 100644 index 00000000000..36c84e49901 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.RecoveryServicesDataReplication' +$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/DataReplication.Management.brown/target/exports/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/exports/README.md new file mode 100644 index 00000000000..e321875284a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.RecoveryServicesDataReplication`. No other cmdlets in this repository are directly exported. What that means is the `Az.RecoveryServicesDataReplication` 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.RecoveryServicesDataReplication.private.dll`) and from the `..\custom\Az.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generate-help.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generate-help.ps1 new file mode 100644 index 00000000000..a51422af3b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..e7d883ca2cd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication' +$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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/Module.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/Module.cs new file mode 100644 index 00000000000..488a38c78cf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication"; + + /// 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.RecoveryServicesDataReplication"; + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/AzureSiteRecoveryManagementServiceApi.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/AzureSiteRecoveryManagementServiceApi.cs new file mode 100644 index 00000000000..5a30cbd5907 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/AzureSiteRecoveryManagementServiceApi.cs @@ -0,0 +1,21893 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Low-level API implementation for the Azure Site Recovery Management Service API service. + /// A first party Azure service enabling the data replication. + /// + public partial class AzureSiteRecoveryManagementServiceApi + { + + /// Checks the resource name availability. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// Resource details. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 CheckNameAvailabilityPost(string subscriptionId, string location, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/locations/" + + global::System.Uri.EscapeDataString(location) + + "/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CheckNameAvailabilityPost_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Checks the resource name availability. + /// + /// Resource details. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 CheckNameAvailabilityPostViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.DataReplication/locations/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.DataReplication/locations/" + + location + + "/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CheckNameAvailabilityPost_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Checks the resource name availability. + /// + /// Resource details. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 CheckNameAvailabilityPostViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.DataReplication/locations/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var location = _match.Groups["location"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.DataReplication/locations/" + + location + + "/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CheckNameAvailabilityPostWithResult_Call (request, eventListener,sender); + } + } + + /// Checks the resource name availability. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// Json string supplied to the CheckNameAvailabilityPost 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CheckNameAvailabilityPostViaJsonString(string subscriptionId, string location, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/locations/" + + global::System.Uri.EscapeDataString(location) + + "/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CheckNameAvailabilityPost_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Checks the resource name availability. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// Json string supplied to the CheckNameAvailabilityPost operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CheckNameAvailabilityPostViaJsonStringWithResult(string subscriptionId, string location, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/locations/" + + global::System.Uri.EscapeDataString(location) + + "/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CheckNameAvailabilityPostWithResult_Call (request, eventListener,sender); + } + } + + /// Checks the resource name availability. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the Azure region. + /// Resource details. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 CheckNameAvailabilityPostWithResult(string subscriptionId, string location, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/locations/" + + global::System.Uri.EscapeDataString(location) + + "/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CheckNameAvailabilityPostWithResult_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.RecoveryServicesDataReplication.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 CheckNameAvailabilityPostWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.CheckNameAvailabilityResponseModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 CheckNameAvailabilityPost_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.CheckNameAvailabilityResponseModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Azure region. + /// Resource details. + /// 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 CheckNameAvailabilityPost_Validate(string subscriptionId, string location, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Performs resource deployment preflight validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Deployment Id. + /// Deployment preflight model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 DeploymentPreflightPost(string subscriptionId, string resourceGroupName, string deploymentId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/deployments/" + + global::System.Uri.EscapeDataString(deploymentId) + + "/preflight" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DeploymentPreflightPost_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs resource deployment preflight validation. + /// + /// Deployment preflight model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 DeploymentPreflightPostViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/deployments/(?[^/]+)$", 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.DataReplication/deployments/{deploymentId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var deploymentId = _match.Groups["deploymentId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/deployments/" + + deploymentId + + "/preflight" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DeploymentPreflightPost_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs resource deployment preflight validation. + /// + /// Deployment preflight model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 DeploymentPreflightPostViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/deployments/(?[^/]+)$", 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.DataReplication/deployments/{deploymentId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var deploymentId = _match.Groups["deploymentId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/deployments/" + + deploymentId + + "/preflight" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DeploymentPreflightPostWithResult_Call (request, eventListener,sender); + } + } + + /// Performs resource deployment preflight validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Deployment Id. + /// Json string supplied to the DeploymentPreflightPost 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DeploymentPreflightPostViaJsonString(string subscriptionId, string resourceGroupName, string deploymentId, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/deployments/" + + global::System.Uri.EscapeDataString(deploymentId) + + "/preflight" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DeploymentPreflightPost_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs resource deployment preflight validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Deployment Id. + /// Json string supplied to the DeploymentPreflightPost operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DeploymentPreflightPostViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string deploymentId, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/deployments/" + + global::System.Uri.EscapeDataString(deploymentId) + + "/preflight" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DeploymentPreflightPostWithResult_Call (request, eventListener,sender); + } + } + + /// Performs resource deployment preflight validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Deployment Id. + /// Deployment preflight model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 DeploymentPreflightPostWithResult(string subscriptionId, string resourceGroupName, string deploymentId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/deployments/" + + global::System.Uri.EscapeDataString(deploymentId) + + "/preflight" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DeploymentPreflightPostWithResult_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.RecoveryServicesDataReplication.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 DeploymentPreflightPostWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 DeploymentPreflightPost_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// Deployment Id. + /// Deployment preflight model. + /// 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 DeploymentPreflightPost_Validate(string subscriptionId, string resourceGroupName, string deploymentId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(deploymentId),deploymentId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// update an alert configuration setting for the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The email configuration name. + /// EmailConfiguration model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EmailConfigurationCreate(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings/" + + global::System.Uri.EscapeDataString(emailConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationCreate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update an alert configuration setting for the given vault. + /// + /// EmailConfiguration model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EmailConfigurationCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/alertSettings/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var emailConfigurationName = _match.Groups["emailConfigurationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/alertSettings/" + + emailConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationCreate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update an alert configuration setting for the given vault. + /// + /// EmailConfiguration model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EmailConfigurationCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/alertSettings/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var emailConfigurationName = _match.Groups["emailConfigurationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/alertSettings/" + + emailConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update an alert configuration setting for the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The email configuration name. + /// Json string supplied to the EmailConfigurationCreate operation + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationCreateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings/" + + global::System.Uri.EscapeDataString(emailConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationCreate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// update an alert configuration setting for the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The email configuration name. + /// Json string supplied to the EmailConfigurationCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings/" + + global::System.Uri.EscapeDataString(emailConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update an alert configuration setting for the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The email configuration name. + /// EmailConfiguration model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EmailConfigurationCreateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings/" + + global::System.Uri.EscapeDataString(emailConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationCreateWithResult_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.RecoveryServicesDataReplication.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 EmailConfigurationCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EmailConfigurationCreate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The email configuration name. + /// EmailConfiguration model. + /// 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 EmailConfigurationCreate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(emailConfigurationName),emailConfigurationName); + await eventListener.AssertRegEx(nameof(emailConfigurationName), emailConfigurationName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Gets the details of the alert configuration setting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The email configuration name. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationGet(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings/" + + global::System.Uri.EscapeDataString(emailConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the alert configuration setting. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/alertSettings/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var emailConfigurationName = _match.Groups["emailConfigurationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/alertSettings/" + + emailConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the alert configuration setting. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/alertSettings/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var emailConfigurationName = _match.Groups["emailConfigurationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/alertSettings/" + + emailConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the alert configuration setting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The email configuration name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings/" + + global::System.Uri.EscapeDataString(emailConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationGetWithResult_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.RecoveryServicesDataReplication.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 EmailConfigurationGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 EmailConfigurationGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The email configuration name. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task EmailConfigurationGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string emailConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(emailConfigurationName),emailConfigurationName); + await eventListener.AssertRegEx(nameof(emailConfigurationName), emailConfigurationName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of alert configuration settings for the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationList(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of alert configuration settings for the given vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/alertSettings$", 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.DataReplication/replicationVaults/{vaultName}/alertSettings'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/alertSettings" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EmailConfigurationList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of alert configuration settings for the given vault. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/alertSettings$", 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.DataReplication/replicationVaults/{vaultName}/alertSettings'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/alertSettings" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of alert configuration settings for the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EmailConfigurationListWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/alertSettings" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EmailConfigurationListWithResult_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.RecoveryServicesDataReplication.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 EmailConfigurationListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 EmailConfigurationList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 EmailConfigurationList_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the event. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The event 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventGet(string subscriptionId, string resourceGroupName, string vaultName, string eventName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/events/" + + global::System.Uri.EscapeDataString(eventName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EventGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the event. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/events/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/events/{eventName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var eventName = _match.Groups["eventName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/events/" + + eventName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EventGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the event. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/events/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/events/{eventName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var eventName = _match.Groups["eventName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/events/" + + eventName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EventGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the event. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The event name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string eventName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/events/" + + global::System.Uri.EscapeDataString(eventName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EventGetWithResult_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.RecoveryServicesDataReplication.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 EventGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 EventGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The event 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 EventGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string eventName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(eventName),eventName); + await eventListener.AssertRegEx(nameof(eventName), eventName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of events in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// OData options. + /// Continuation token. + /// Page size. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventList(string subscriptionId, string resourceGroupName, string vaultName, string odataOptions, string continuationToken, int? pageSize, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/events" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EventList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of events in the given vault. + /// + /// OData options. + /// Continuation token. + /// Page size. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventListViaIdentity(global::System.String viaIdentity, string odataOptions, string continuationToken, int? pageSize, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/events$", 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.DataReplication/replicationVaults/{vaultName}/events'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/events" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.EventList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of events in the given vault. + /// + /// OData options. + /// Continuation token. + /// Page size. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventListViaIdentityWithResult(global::System.String viaIdentity, string odataOptions, string continuationToken, int? pageSize, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/events$", 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.DataReplication/replicationVaults/{vaultName}/events'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/events" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EventListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of events in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// OData options. + /// Continuation token. + /// Page size. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task EventListWithResult(string subscriptionId, string resourceGroupName, string vaultName, string odataOptions, string continuationToken, int? pageSize, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/events" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.EventListWithResult_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.RecoveryServicesDataReplication.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 EventListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 EventList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// OData options. + /// Continuation token. + /// Page size. + /// The vault 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 EventList_Validate(string subscriptionId, string resourceGroupName, string odataOptions, string continuationToken, int? pageSize, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(odataOptions),odataOptions); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// update the fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent name. + /// Fabric agent model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricAgentCreate(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the fabric agent. + /// + /// Fabric agent model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricAgentCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + var fabricAgentName = _match.Groups["fabricAgentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents/" + + fabricAgentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the fabric agent. + /// + /// Fabric agent model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricAgentCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + var fabricAgentName = _match.Groups["fabricAgentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents/" + + fabricAgentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent name. + /// Json string supplied to the FabricAgentCreate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentCreateViaJsonString(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent name. + /// Json string supplied to the FabricAgentCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent name. + /// Fabric agent model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricAgentCreateWithResult(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentCreateWithResult_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.RecoveryServicesDataReplication.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 FabricAgentCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricAgentCreate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric name. + /// The fabric agent name. + /// Fabric agent model. + /// 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 FabricAgentCreate_Validate(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(fabricAgentName),fabricAgentName); + await eventListener.AssertRegEx(nameof(fabricAgentName), fabricAgentName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentDelete(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Deletes fabric agent. + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + var fabricAgentName = _match.Groups["fabricAgentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents/" + + fabricAgentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentDelete_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.RecoveryServicesDataReplication.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 FabricAgentDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric name. + /// The fabric agent 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 FabricAgentDelete_Validate(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(fabricAgentName),fabricAgentName); + await eventListener.AssertRegEx(nameof(fabricAgentName), fabricAgentName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentGet(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the fabric agent. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + var fabricAgentName = _match.Groups["fabricAgentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents/" + + fabricAgentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the fabric agent. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + var fabricAgentName = _match.Groups["fabricAgentName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents/" + + fabricAgentName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the fabric agent. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// The fabric agent name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentGetWithResult(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents/" + + global::System.Uri.EscapeDataString(fabricAgentName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentGetWithResult_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.RecoveryServicesDataReplication.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 FabricAgentGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricAgentGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric name. + /// The fabric agent 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 FabricAgentGet_Validate(string subscriptionId, string resourceGroupName, string fabricName, string fabricAgentName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(fabricAgentName),fabricAgentName); + await eventListener.AssertRegEx(nameof(fabricAgentName), fabricAgentName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of fabric agents in the given fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentList(string subscriptionId, string resourceGroupName, string fabricName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of fabric agents in the given fabric. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricAgentList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of fabric agents in the given fabric. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)/fabricAgents$", 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.DataReplication/replicationFabrics/{fabricName}/fabricAgents'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "/fabricAgents" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of fabric agents in the given fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricAgentListWithResult(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "/fabricAgents" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricAgentListWithResult_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.RecoveryServicesDataReplication.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 FabricAgentListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricAgentList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric 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 FabricAgentList_Validate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + } + } + + /// create the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Fabric properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricCreate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create the fabric. + /// + /// Fabric properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create the fabric. + /// + /// Fabric properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Json string supplied to the FabricCreate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricCreateViaJsonString(string subscriptionId, string resourceGroupName, string fabricName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Json string supplied to the FabricCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fabricName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Fabric properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricCreateWithResult(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricCreateWithResult_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.RecoveryServicesDataReplication.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 FabricCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricCreate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric name. + /// Fabric properties. + /// 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 FabricCreate_Validate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Removes the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricDelete(string subscriptionId, string resourceGroupName, string fabricName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Removes the fabric. + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricDelete_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.RecoveryServicesDataReplication.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 FabricDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric 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 FabricDelete_Validate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricGet(string subscriptionId, string resourceGroupName, string fabricName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the fabric. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the fabric. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricGetWithResult(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricGetWithResult_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.RecoveryServicesDataReplication.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 FabricGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric 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 FabricGet_Validate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of fabrics in the given subscription and 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. + /// Continuation token from the previous call. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricList(string subscriptionId, string resourceGroupName, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of fabrics in the given 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of fabrics in the given 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListBySubscriptionViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationFabrics'"); + } + + // 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.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of fabrics in the given subscription. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationFabrics'"); + } + + // 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.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of fabrics in the given 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricListBySubscriptionWithResult_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.RecoveryServicesDataReplication.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 FabricListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricListBySubscription_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + } + } + + /// Gets the list of fabrics in the given subscription and resource group. + /// + /// Continuation token from the previous call. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListViaIdentity(global::System.String viaIdentity, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics$", 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.DataReplication/replicationFabrics'"); + } + + // 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.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of fabrics in the given subscription and resource group. + /// + /// Continuation token from the previous call. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListViaIdentityWithResult(global::System.String viaIdentity, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics$", 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.DataReplication/replicationFabrics'"); + } + + // 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.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of fabrics in the given subscription and 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. + /// Continuation token from the previous call. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricListWithResult(string subscriptionId, string resourceGroupName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricListWithResult_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.RecoveryServicesDataReplication.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 FabricListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// Continuation token from the previous call. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task FabricList_Validate(string subscriptionId, string resourceGroupName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + + /// Performs update on the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Fabric properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricUpdate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the fabric. + /// + /// Fabric properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the fabric. + /// + /// Fabric properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationFabrics/(?[^/]+)$", 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.DataReplication/replicationFabrics/{fabricName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fabricName = _match.Groups["fabricName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationFabrics/" + + fabricName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Performs update on the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Json string supplied to the FabricUpdate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fabricName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FabricUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Json string supplied to the FabricUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FabricUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fabricName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Performs update on the fabric. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The fabric name. + /// Fabric properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricUpdateWithResult(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationFabrics/" + + global::System.Uri.EscapeDataString(fabricName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FabricUpdateWithResult_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.RecoveryServicesDataReplication.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 FabricUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricUpdate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The fabric name. + /// Fabric properties. + /// 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 FabricUpdate_Validate(string subscriptionId, string resourceGroupName, string fabricName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fabricName),fabricName); + await eventListener.AssertRegEx(nameof(fabricName), fabricName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Gets the details of the job. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The job 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobGet(string subscriptionId, string resourceGroupName, string vaultName, string jobName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/jobs/" + + global::System.Uri.EscapeDataString(jobName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.JobGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the job. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/jobs/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var jobName = _match.Groups["jobName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/jobs/" + + jobName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.JobGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the job. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/jobs/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var jobName = _match.Groups["jobName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/jobs/" + + jobName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.JobGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the job. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The job name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string jobName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/jobs/" + + global::System.Uri.EscapeDataString(jobName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.JobGetWithResult_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.RecoveryServicesDataReplication.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 JobGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 JobGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The job 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 JobGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string jobName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(jobName),jobName); + await eventListener.AssertRegEx(nameof(jobName), jobName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of jobs in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// OData options. + /// Continuation token. + /// Page size. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobList(string subscriptionId, string resourceGroupName, string vaultName, string odataOptions, string continuationToken, int? pageSize, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/jobs" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.JobList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of jobs in the given vault. + /// + /// OData options. + /// Continuation token. + /// Page size. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobListViaIdentity(global::System.String viaIdentity, string odataOptions, string continuationToken, int? pageSize, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/jobs$", 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.DataReplication/replicationVaults/{vaultName}/jobs'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/jobs" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.JobList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of jobs in the given vault. + /// + /// OData options. + /// Continuation token. + /// Page size. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobListViaIdentityWithResult(global::System.String viaIdentity, string odataOptions, string continuationToken, int? pageSize, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/jobs$", 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.DataReplication/replicationVaults/{vaultName}/jobs'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/jobs" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.JobListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of jobs in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// OData options. + /// Continuation token. + /// Page size. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task JobListWithResult(string subscriptionId, string resourceGroupName, string vaultName, string odataOptions, string continuationToken, int? pageSize, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/jobs" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.JobListWithResult_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.RecoveryServicesDataReplication.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 JobListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 JobList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// OData options. + /// Continuation token. + /// Page size. + /// The vault 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 JobList_Validate(string subscriptionId, string resourceGroupName, string odataOptions, string continuationToken, int? pageSize, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(odataOptions),odataOptions); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the location based operation result. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure region. + /// The ID of an ongoing async 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task LocationBasedOperationResultsGet(string subscriptionId, string resourceGroupName, string location, string operationId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/locations/" + + global::System.Uri.EscapeDataString(location) + + "/operationResults/" + + global::System.Uri.EscapeDataString(operationId) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.LocationBasedOperationResultsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the location based operation result. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task LocationBasedOperationResultsGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/locations/(?[^/]+)/operationResults/(?[^/]+)$", 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.DataReplication/locations/{location}/operationResults/{operationId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var location = _match.Groups["location"].Value; + var operationId = _match.Groups["operationId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/locations/" + + location + + "/operationResults/" + + operationId + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.LocationBasedOperationResultsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the location based operation result. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task LocationBasedOperationResultsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/locations/(?[^/]+)/operationResults/(?[^/]+)$", 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.DataReplication/locations/{location}/operationResults/{operationId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var location = _match.Groups["location"].Value; + var operationId = _match.Groups["operationId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/locations/" + + location + + "/operationResults/" + + operationId + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.LocationBasedOperationResultsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the location based operation result. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Azure region. + /// The ID of an ongoing async operation. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task LocationBasedOperationResultsGetWithResult(string subscriptionId, string resourceGroupName, string location, string operationId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/locations/" + + global::System.Uri.EscapeDataString(location) + + "/operationResults/" + + global::System.Uri.EscapeDataString(operationId) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.LocationBasedOperationResultsGetWithResult_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.RecoveryServicesDataReplication.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 LocationBasedOperationResultsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationStatus.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 LocationBasedOperationResultsGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationStatus.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The name of the Azure region. + /// The ID of an ongoing async operation. + /// 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 LocationBasedOperationResultsGet_Validate(string subscriptionId, string resourceGroupName, string location, string operationId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertMinimumLength(nameof(location),location,1); + await eventListener.AssertNotNull(nameof(operationId),operationId); + await eventListener.AssertMinimumLength(nameof(operationId),operationId,1); + } + } + + /// Gets the operations. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The ID of an ongoing async 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationResultsGet(string subscriptionId, string resourceGroupName, string operationId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/operationResults/" + + global::System.Uri.EscapeDataString(operationId) + + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationResultsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the operations. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationResultsGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/operationResults/(?[^/]+)/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}$", 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.DataReplication/operationResults/{operationId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var operationId = _match.Groups["operationId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/operationResults/" + + operationId + + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationResultsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the operations. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationResultsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/operationResults/(?[^/]+)/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}$", 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.DataReplication/operationResults/{operationId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var operationId = _match.Groups["operationId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/operationResults/" + + operationId + + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationResultsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the operations. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The ID of an ongoing async operation. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationResultsGetWithResult(string subscriptionId, string resourceGroupName, string operationId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/operationResults/" + + global::System.Uri.EscapeDataString(operationId) + + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationResultsGetWithResult_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.RecoveryServicesDataReplication.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 OperationResultsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationStatus.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 OperationResultsGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationStatus.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The ID of an ongoing async operation. + /// 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 OperationResultsGet_Validate(string subscriptionId, string resourceGroupName, string operationId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(operationId),operationId); + await eventListener.AssertMinimumLength(nameof(operationId),operationId,1); + } + } + + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.DataReplication/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.DataReplication/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.DataReplication/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.DataReplication/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.DataReplication/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.DataReplication/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.DataReplication/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.DataReplication/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// update the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy name. + /// Policy model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PolicyCreate(string subscriptionId, string resourceGroupName, string vaultName, string policyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the policy. + /// + /// Policy model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PolicyCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var policyName = _match.Groups["policyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies/" + + policyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the policy. + /// + /// Policy model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PolicyCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var policyName = _match.Groups["policyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies/" + + policyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy name. + /// Json string supplied to the PolicyCreate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyCreateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string policyName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy name. + /// Json string supplied to the PolicyCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string policyName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy name. + /// Policy model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PolicyCreateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string policyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyCreateWithResult_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.RecoveryServicesDataReplication.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 PolicyCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PolicyCreate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The policy name. + /// Policy model. + /// 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 PolicyCreate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string policyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(policyName),policyName); + await eventListener.AssertRegEx(nameof(policyName), policyName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Removes the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyDelete(string subscriptionId, string resourceGroupName, string vaultName, string policyName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Removes the policy. + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var policyName = _match.Groups["policyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies/" + + policyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyDelete_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.RecoveryServicesDataReplication.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 PolicyDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The policy 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 PolicyDelete_Validate(string subscriptionId, string resourceGroupName, string vaultName, string policyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(policyName),policyName); + await eventListener.AssertRegEx(nameof(policyName), policyName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyGet(string subscriptionId, string resourceGroupName, string vaultName, string policyName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the policy. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var policyName = _match.Groups["policyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies/" + + policyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the policy. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var policyName = _match.Groups["policyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies/" + + policyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the policy. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The policy name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string policyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies/" + + global::System.Uri.EscapeDataString(policyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyGetWithResult_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.RecoveryServicesDataReplication.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 PolicyGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PolicyGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The policy 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 PolicyGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string policyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(policyName),policyName); + await eventListener.AssertRegEx(nameof(policyName), policyName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of policies in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyList(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of policies in the given vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PolicyList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of policies in the given vault. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationPolicies$", 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.DataReplication/replicationVaults/{vaultName}/replicationPolicies'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationPolicies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of policies in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PolicyListWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationPolicies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PolicyListWithResult_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.RecoveryServicesDataReplication.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 PolicyListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PolicyList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 PolicyList_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// Private endpoint connection creation input. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesCreate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesCreate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// + /// Private endpoint connection creation input. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesCreate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// + /// Private endpoint connection creation input. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// Json string supplied to the PrivateEndpointConnectionProxiesCreate operation + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesCreateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesCreate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// Json string supplied to the PrivateEndpointConnectionProxiesCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// Private endpoint connection creation input. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesCreateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesCreateWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesCreate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection proxy name. + /// Private endpoint connection creation input. + /// 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 PrivateEndpointConnectionProxiesCreate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionProxyName),privateEndpointConnectionProxyName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionProxyName), privateEndpointConnectionProxyName, @"^[a-zA-Z0-9-.]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// Returns the operation to track the deletion of private endpoint connection proxy. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesDelete(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Returns the operation to track the deletion of private endpoint connection proxy. + /// + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesDelete_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection proxy 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 PrivateEndpointConnectionProxiesDelete_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionProxyName),privateEndpointConnectionProxyName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionProxyName), privateEndpointConnectionProxyName, @"^[a-zA-Z0-9-.]*$"); + } + } + + /// Gets the private endpoint connection proxy details. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesGet(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the private endpoint connection proxy details. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the private endpoint connection proxy details. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the private endpoint connection proxy details. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesGetWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection proxy 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 PrivateEndpointConnectionProxiesGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionProxyName),privateEndpointConnectionProxyName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionProxyName), privateEndpointConnectionProxyName, @"^[a-zA-Z0-9-.]*$"); + } + } + + /// Gets the all private endpoint connections proxies. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesList(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the all private endpoint connections proxies. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the all private endpoint connections proxies. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the all private endpoint connections proxies. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesListWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesListWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 PrivateEndpointConnectionProxiesList_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Returns remote private endpoint connection information after validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// The private endpoint connection proxy input. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesValidate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "/validate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesValidate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Returns remote private endpoint connection information after validation. + /// + /// The private endpoint connection proxy input. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesValidateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "/validate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesValidate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Returns remote private endpoint connection information after validation. + /// + /// The private endpoint connection proxy input. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesValidateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnectionProxies/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionProxyName = _match.Groups["privateEndpointConnectionProxyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnectionProxies/" + + privateEndpointConnectionProxyName + + "/validate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesValidateWithResult_Call (request, eventListener,sender); + } + } + + /// Returns remote private endpoint connection information after validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// Json string supplied to the PrivateEndpointConnectionProxiesValidate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesValidateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "/validate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionProxiesValidate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Returns remote private endpoint connection information after validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// Json string supplied to the PrivateEndpointConnectionProxiesValidate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionProxiesValidateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "/validate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesValidateWithResult_Call (request, eventListener,sender); + } + } + + /// Returns remote private endpoint connection information after validation. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection proxy name. + /// The private endpoint connection proxy input. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesValidateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnectionProxies/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionProxyName) + + "/validate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionProxiesValidateWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesValidateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxiesValidate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection proxy name. + /// The private endpoint connection proxy input. + /// 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 PrivateEndpointConnectionProxiesValidate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionProxyName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionProxyName),privateEndpointConnectionProxyName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionProxyName), privateEndpointConnectionProxyName, @"^[a-zA-Z0-9-.]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the private endpoint connection. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsDelete(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Deletes the private endpoint connection. + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsDelete_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection 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 PrivateEndpointConnectionsDelete_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionName),privateEndpointConnectionName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionName), privateEndpointConnectionName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the private endpoint connection details. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGet(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the private endpoint connection details. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the private endpoint connection details. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the private endpoint connection details. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsGetWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection 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 PrivateEndpointConnectionsGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionName),privateEndpointConnectionName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionName), privateEndpointConnectionName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the all private endpoint connections configured on the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsList(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the all private endpoint connections configured on the vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the all private endpoint connections configured on the vault. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the all private endpoint connections configured on the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsListWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsListWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 PrivateEndpointConnectionsList_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// + /// Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection name. + /// Private endpoint connection update input. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsUpdate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + /// + /// + /// Private endpoint connection update input. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + /// + /// + /// Private endpoint connection update input. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateEndpointConnections/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateEndpointConnectionName = _match.Groups["privateEndpointConnectionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateEndpointConnections/" + + privateEndpointConnectionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection name. + /// Json string supplied to the PrivateEndpointConnectionsUpdate operation + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateEndpointConnectionsUpdate_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection name. + /// Json string supplied to the PrivateEndpointConnectionsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateEndpointConnectionsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Updated the private endpoint connection status (Approval/Rejected). This gets invoked by resource admin. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private endpoint connection name. + /// Private endpoint connection update input. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsUpdateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateEndpointConnections/" + + global::System.Uri.EscapeDataString(privateEndpointConnectionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateEndpointConnectionsUpdateWithResult_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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionsUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private endpoint connection name. + /// Private endpoint connection update input. + /// 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 PrivateEndpointConnectionsUpdate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateEndpointConnectionName),privateEndpointConnectionName); + await eventListener.AssertRegEx(nameof(privateEndpointConnectionName), privateEndpointConnectionName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Gets the details of site recovery private link resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private link 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGet(string subscriptionId, string resourceGroupName, string vaultName, string privateLinkResourceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateLinkResources/" + + global::System.Uri.EscapeDataString(privateLinkResourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of site recovery private link 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateLinkResources/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateLinkResources/{privateLinkResourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateLinkResourceName = _match.Groups["privateLinkResourceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateLinkResources/" + + privateLinkResourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of site recovery private link resource. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateLinkResources/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/privateLinkResources/{privateLinkResourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var privateLinkResourceName = _match.Groups["privateLinkResourceName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateLinkResources/" + + privateLinkResourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of site recovery private link resource. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The private link name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string privateLinkResourceName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateLinkResources/" + + global::System.Uri.EscapeDataString(privateLinkResourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesGetWithResult_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.RecoveryServicesDataReplication.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 PrivateLinkResourcesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateLinkResourcesGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The private link 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 PrivateLinkResourcesGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string privateLinkResourceName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(privateLinkResourceName),privateLinkResourceName); + await eventListener.AssertRegEx(nameof(privateLinkResourceName), privateLinkResourceName, @"^[a-zA-Z0-9-.]*$"); + } + } + + /// Gets the list of private link resources. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesList(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of private link resources. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateLinkResources$", 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.DataReplication/replicationVaults/{vaultName}/privateLinkResources'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PrivateLinkResourcesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of private link resources. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/privateLinkResources$", 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.DataReplication/replicationVaults/{vaultName}/privateLinkResources'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of private link resources. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PrivateLinkResourcesListWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/privateLinkResources" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PrivateLinkResourcesListWithResult_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.RecoveryServicesDataReplication.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 PrivateLinkResourcesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 PrivateLinkResourcesList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 PrivateLinkResourcesList_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// create the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Protected item model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemCreate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create the protected item. + /// + /// Protected item model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create the protected item. + /// + /// Protected item model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Json string supplied to the ProtectedItemCreate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemCreateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Json string supplied to the ProtectedItemCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Protected item model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemCreateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemCreateWithResult_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.RecoveryServicesDataReplication.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 ProtectedItemCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ProtectedItemCreate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The protected item name. + /// Protected item model. + /// 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 ProtectedItemCreate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Removes the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// A flag indicating whether to do force delete or not. + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemDelete(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, bool? forceDelete, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == forceDelete ? global::System.String.Empty : "forceDelete=" + global::System.Uri.EscapeDataString(forceDelete.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Removes the protected item. + /// + /// A flag indicating whether to do force delete or not. + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemDeleteViaIdentity(global::System.String viaIdentity, bool? forceDelete, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == forceDelete ? global::System.String.Empty : "forceDelete=" + global::System.Uri.EscapeDataString(forceDelete.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemDelete_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.RecoveryServicesDataReplication.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 ProtectedItemDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// A flag indicating whether to do force delete or not. + /// The vault name. + /// The protected item 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 ProtectedItemDelete_Validate(string subscriptionId, string resourceGroupName, bool? forceDelete, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemGet(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the protected item. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the protected item. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemGetWithResult_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.RecoveryServicesDataReplication.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 ProtectedItemGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ProtectedItemGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The protected item 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 ProtectedItemGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of protected items in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// OData options. + /// Continuation token. + /// Page size. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemList(string subscriptionId, string resourceGroupName, string vaultName, string odataOptions, string continuationToken, int? pageSize, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of protected items in the given vault. + /// + /// OData options. + /// Continuation token. + /// Page size. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemListViaIdentity(global::System.String viaIdentity, string odataOptions, string continuationToken, int? pageSize, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of protected items in the given vault. + /// + /// OData options. + /// Continuation token. + /// Page size. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemListViaIdentityWithResult(global::System.String viaIdentity, string odataOptions, string continuationToken, int? pageSize, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of protected items in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// OData options. + /// Continuation token. + /// Page size. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemListWithResult(string subscriptionId, string resourceGroupName, string vaultName, string odataOptions, string continuationToken, int? pageSize, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(odataOptions) ? global::System.String.Empty : "odataOptions=" + global::System.Uri.EscapeDataString(odataOptions)) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + + "&" + + (null == pageSize ? global::System.String.Empty : "pageSize=" + global::System.Uri.EscapeDataString(pageSize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemListWithResult_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.RecoveryServicesDataReplication.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 ProtectedItemListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ProtectedItemList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// OData options. + /// Continuation token. + /// Page size. + /// The vault 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 ProtectedItemList_Validate(string subscriptionId, string resourceGroupName, string odataOptions, string continuationToken, int? pageSize, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(odataOptions),odataOptions); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Performs the planned failover on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Planned failover model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemPlannedFailover(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/plannedFailover" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemPlannedFailover_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs the planned failover on the protected item. + /// + /// Planned failover model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemPlannedFailoverViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "/plannedFailover" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemPlannedFailover_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs the planned failover on the protected item. + /// + /// Planned failover model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemPlannedFailoverViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "/plannedFailover" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemPlannedFailoverWithResult_Call (request, eventListener,sender); + } + } + + /// Performs the planned failover on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Json string supplied to the ProtectedItemPlannedFailover 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemPlannedFailoverViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/plannedFailover" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemPlannedFailover_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs the planned failover on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Json string supplied to the ProtectedItemPlannedFailover operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemPlannedFailoverViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/plannedFailover" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemPlannedFailoverWithResult_Call (request, eventListener,sender); + } + } + + /// Performs the planned failover on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Planned failover model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemPlannedFailoverWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/plannedFailover" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemPlannedFailoverWithResult_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.RecoveryServicesDataReplication.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 ProtectedItemPlannedFailoverWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ProtectedItemPlannedFailover_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The protected item name. + /// Planned failover model. + /// 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 ProtectedItemPlannedFailover_Validate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Performs update on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Protected item model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemUpdate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the protected item. + /// + /// Protected item model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the protected item. + /// + /// Protected item model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Performs update on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Json string supplied to the ProtectedItemUpdate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemUpdateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProtectedItemUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Json string supplied to the ProtectedItemUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ProtectedItemUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Performs update on the protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// Protected item model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemUpdateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ProtectedItemUpdateWithResult_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.RecoveryServicesDataReplication.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 ProtectedItemUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ProtectedItemUpdate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The protected item name. + /// Protected item model. + /// 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 ProtectedItemUpdate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Gets the details of the recovery point of a protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// The recovery point 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointGet(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, string recoveryPointName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/recoveryPoints/" + + global::System.Uri.EscapeDataString(recoveryPointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.RecoveryPointGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the recovery point of a protected item. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)/recoveryPoints/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + var recoveryPointName = _match.Groups["recoveryPointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "/recoveryPoints/" + + recoveryPointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.RecoveryPointGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the recovery point of a protected item. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)/recoveryPoints/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + var recoveryPointName = _match.Groups["recoveryPointName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "/recoveryPoints/" + + recoveryPointName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.RecoveryPointGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the recovery point of a protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// The recovery point name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, string recoveryPointName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/recoveryPoints/" + + global::System.Uri.EscapeDataString(recoveryPointName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.RecoveryPointGetWithResult_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.RecoveryServicesDataReplication.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 RecoveryPointGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 RecoveryPointGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The protected item name. + /// The recovery point 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 RecoveryPointGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, string recoveryPointName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(recoveryPointName),recoveryPointName); + await eventListener.AssertRegEx(nameof(recoveryPointName), recoveryPointName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of recovery points of the given protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointList(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/recoveryPoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.RecoveryPointList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of recovery points of the given protected item. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)/recoveryPoints$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "/recoveryPoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.RecoveryPointList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of recovery points of the given protected item. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/protectedItems/(?[^/]+)/recoveryPoints$", 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.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var protectedItemName = _match.Groups["protectedItemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/protectedItems/" + + protectedItemName + + "/recoveryPoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.RecoveryPointListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of recovery points of the given protected item. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The protected item name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task RecoveryPointListWithResult(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/protectedItems/" + + global::System.Uri.EscapeDataString(protectedItemName) + + "/recoveryPoints" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.RecoveryPointListWithResult_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.RecoveryServicesDataReplication.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 RecoveryPointListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 RecoveryPointList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The protected item 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 RecoveryPointList_Validate(string subscriptionId, string resourceGroupName, string vaultName, string protectedItemName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(protectedItemName),protectedItemName); + await eventListener.AssertRegEx(nameof(protectedItemName), protectedItemName, @"^[a-zA-Z0-9]*$"); + } + } + + /// update the replication extension in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension name. + /// Replication extension model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ReplicationExtensionCreate(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the replication extension in the given vault. + /// + /// Replication extension model. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ReplicationExtensionCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var replicationExtensionName = _match.Groups["replicationExtensionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions/" + + replicationExtensionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the replication extension in the given vault. + /// + /// Replication extension model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ReplicationExtensionCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var replicationExtensionName = _match.Groups["replicationExtensionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions/" + + replicationExtensionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the replication extension in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension name. + /// Json string supplied to the ReplicationExtensionCreate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionCreateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the replication extension in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension name. + /// Json string supplied to the ReplicationExtensionCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the replication extension in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension name. + /// Replication extension model. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ReplicationExtensionCreateWithResult(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionCreateWithResult_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.RecoveryServicesDataReplication.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 ReplicationExtensionCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ReplicationExtensionCreate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The replication extension name. + /// Replication extension model. + /// 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 ReplicationExtensionCreate_Validate(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(replicationExtensionName),replicationExtensionName); + await eventListener.AssertRegEx(nameof(replicationExtensionName), replicationExtensionName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the replication extension in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionDelete(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Deletes the replication extension in the given vault. + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var replicationExtensionName = _match.Groups["replicationExtensionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions/" + + replicationExtensionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionDelete_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.RecoveryServicesDataReplication.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 ReplicationExtensionDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The replication extension 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 ReplicationExtensionDelete_Validate(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(replicationExtensionName),replicationExtensionName); + await eventListener.AssertRegEx(nameof(replicationExtensionName), replicationExtensionName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the replication extension. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionGet(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the replication extension. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var replicationExtensionName = _match.Groups["replicationExtensionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions/" + + replicationExtensionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the replication extension. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var replicationExtensionName = _match.Groups["replicationExtensionName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions/" + + replicationExtensionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the replication extension. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// The replication extension name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions/" + + global::System.Uri.EscapeDataString(replicationExtensionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionGetWithResult_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.RecoveryServicesDataReplication.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 ReplicationExtensionGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ReplicationExtensionGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// The replication extension 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 ReplicationExtensionGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, string replicationExtensionName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(replicationExtensionName),replicationExtensionName); + await eventListener.AssertRegEx(nameof(replicationExtensionName), replicationExtensionName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of replication extensions in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionList(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of replication extensions in the given vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionListViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ReplicationExtensionList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of replication extensions in the given vault. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)/replicationExtensions$", 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.DataReplication/replicationVaults/{vaultName}/replicationExtensions'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "/replicationExtensions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of replication extensions in the given vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ReplicationExtensionListWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/replicationExtensions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.ReplicationExtensionListWithResult_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.RecoveryServicesDataReplication.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 ReplicationExtensionListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 ReplicationExtensionList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 ReplicationExtensionList_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// update the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Vault properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultCreate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the vault. + /// + /// Vault properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the vault. + /// + /// Vault properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Json string supplied to the VaultCreate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultCreateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Json string supplied to the VaultCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Vault properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultCreateWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultCreateWithResult_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.RecoveryServicesDataReplication.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 VaultCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultCreate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// Vault properties. + /// 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 VaultCreate_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Removes the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultDelete(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Removes the vault. + /// + /// 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultDeleteViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultDelete_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.RecoveryServicesDataReplication.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 VaultDelete_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 VaultDelete_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the details of the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultGet(string subscriptionId, string resourceGroupName, string vaultName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultGetViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the details of the vault. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the details of the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultGetWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultGetWithResult_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.RecoveryServicesDataReplication.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 VaultGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultGet_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault 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 VaultGet_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[a-zA-Z0-9]*$"); + } + } + + /// Gets the list of vaults in the given subscription and 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. + /// Continuation token from the previous call. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultList(string subscriptionId, string resourceGroupName, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of vaults in the given 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of vaults in the given 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListBySubscriptionViaIdentity(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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationVaults'"); + } + + // 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.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of vaults in the given subscription. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationVaults'"); + } + + // 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.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of vaults in the given 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultListBySubscriptionWithResult_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.RecoveryServicesDataReplication.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 VaultListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultListBySubscription_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + } + } + + /// Gets the list of vaults in the given subscription and resource group. + /// + /// Continuation token from the previous call. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListViaIdentity(global::System.String viaIdentity, string continuationToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults$", 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.DataReplication/replicationVaults'"); + } + + // 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.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets the list of vaults in the given subscription and resource group. + /// + /// Continuation token from the previous call. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListViaIdentityWithResult(global::System.String viaIdentity, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults$", 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.DataReplication/replicationVaults'"); + } + + // 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.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultListWithResult_Call (request, eventListener,sender); + } + } + + /// Gets the list of vaults in the given subscription and 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. + /// Continuation token from the previous call. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultListWithResult(string subscriptionId, string resourceGroupName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(continuationToken) ? global::System.String.Empty : "continuationToken=" + global::System.Uri.EscapeDataString(continuationToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultListWithResult_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.RecoveryServicesDataReplication.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 VaultListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultList_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// Continuation token from the previous call. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task VaultList_Validate(string subscriptionId, string resourceGroupName, string continuationToken, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(continuationToken),continuationToken); + } + } + + /// Performs update on the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Vault properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultUpdate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the vault. + /// + /// Vault properties. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the vault. + /// + /// Vault properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.DataReplication/replicationVaults/(?[^/]+)$", 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.DataReplication/replicationVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.DataReplication/replicationVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Performs update on the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Json string supplied to the VaultUpdate 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.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultUpdateViaJsonString(string subscriptionId, string resourceGroupName, string vaultName, 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Performs update on the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Json string supplied to the VaultUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task VaultUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string vaultName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Performs update on the vault. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The vault name. + /// Vault properties. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultUpdateWithResult(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-09-01"; + // 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.DataReplication/replicationVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.VaultUpdateWithResult_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.RecoveryServicesDataReplication.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 VaultUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultUpdate_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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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. + /// The vault name. + /// Vault properties. + /// 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 VaultUpdate_Validate(string subscriptionId, string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate body, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName), vaultName, @"^[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/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.PowerShell.cs new file mode 100644 index 00000000000..f660aeb006a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Details of the affected object. + [System.ComponentModel.TypeConverter(typeof(AffectedObjectDetailsTypeConverter))] + public partial class AffectedObjectDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AffectedObjectDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)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 AffectedObjectDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AffectedObjectDetails(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AffectedObjectDetails(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 the affected object. + [System.ComponentModel.TypeConverter(typeof(AffectedObjectDetailsTypeConverter))] + public partial interface IAffectedObjectDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.TypeConverter.cs new file mode 100644 index 00000000000..775257ca0bb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AffectedObjectDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IAffectedObjectDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AffectedObjectDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AffectedObjectDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AffectedObjectDetails.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.cs new file mode 100644 index 00000000000..3fc6587fb2f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Details of the affected object. + public partial class AffectedObjectDetails : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal + { + + /// Backing field for property. + private string _description; + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _type; + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public AffectedObjectDetails() + { + + } + } + /// Details of the affected object. + public partial interface IAffectedObjectDetails : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Description of the affected object details.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Type of the affected object details.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string Type { get; set; } + + } + /// Details of the affected object. + internal partial interface IAffectedObjectDetailsInternal + + { + /// Description of the affected object details. + string Description { get; set; } + /// Type of the affected object details. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.json.cs new file mode 100644 index 00000000000..6c8db85e385 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AffectedObjectDetails.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Details of the affected object. + public partial class AffectedObjectDetails + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal AffectedObjectDetails(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new AffectedObjectDetails(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..82c3cb0e0f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..c23d2c5ac24 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..587e3cb6ddc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..2176d5ab377 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Any.json.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IAny. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.PowerShell.cs new file mode 100644 index 00000000000..e47be8adeda --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// AzStackHCI cluster properties. + [System.ComponentModel.TypeConverter(typeof(AzStackHciClusterPropertiesTypeConverter))] + public partial class AzStackHciClusterProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AzStackHciClusterProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ClusterName, global::System.Convert.ToString); + } + if (content.Contains("ResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ResourceName, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageAccountName = (string) content.GetValueForProperty("StorageAccountName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageAccountName, global::System.Convert.ToString); + } + if (content.Contains("StorageContainer")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageContainer = (System.Collections.Generic.List) content.GetValueForProperty("StorageContainer",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageContainer, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.StorageContainerPropertiesTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AzStackHciClusterProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ClusterName, global::System.Convert.ToString); + } + if (content.Contains("ResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).ResourceName, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageAccountName = (string) content.GetValueForProperty("StorageAccountName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageAccountName, global::System.Convert.ToString); + } + if (content.Contains("StorageContainer")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageContainer = (System.Collections.Generic.List) content.GetValueForProperty("StorageContainer",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)this).StorageContainer, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.StorageContainerPropertiesTypeConverter.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.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AzStackHciClusterProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AzStackHciClusterProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// AzStackHCI cluster properties. + [System.ComponentModel.TypeConverter(typeof(AzStackHciClusterPropertiesTypeConverter))] + public partial interface IAzStackHciClusterProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.TypeConverter.cs new file mode 100644 index 00000000000..6b3ef11819f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AzStackHciClusterPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AzStackHciClusterProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AzStackHciClusterProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AzStackHciClusterProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.cs new file mode 100644 index 00000000000..c1068de8468 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// AzStackHCI cluster properties. + public partial class AzStackHciClusterProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal + { + + /// Backing field for property. + private string _clusterName; + + /// Gets or sets the AzStackHCICluster FQDN name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _resourceName; + + /// Gets or sets the AzStackHCICluster resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _storageAccountName; + + /// Gets or sets the Storage account name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageAccountName { get => this._storageAccountName; set => this._storageAccountName = value; } + + /// Backing field for property. + private System.Collections.Generic.List _storageContainer; + + /// Gets or sets the list of AzStackHCICluster Storage Container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List StorageContainer { get => this._storageContainer; set => this._storageContainer = value; } + + /// Creates an new instance. + public AzStackHciClusterProperties() + { + + } + } + /// AzStackHCI cluster properties. + public partial interface IAzStackHciClusterProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the AzStackHCICluster FQDN name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the AzStackHCICluster FQDN name.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + string ClusterName { get; set; } + /// Gets or sets the AzStackHCICluster resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the AzStackHCICluster resource name.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + string ResourceName { get; set; } + /// Gets or sets the Storage account name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Storage account name.", + SerializedName = @"storageAccountName", + PossibleTypes = new [] { typeof(string) })] + string StorageAccountName { get; set; } + /// Gets or sets the list of AzStackHCICluster Storage Container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of AzStackHCICluster Storage Container.", + SerializedName = @"storageContainers", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties) })] + System.Collections.Generic.List StorageContainer { get; set; } + + } + /// AzStackHCI cluster properties. + internal partial interface IAzStackHciClusterPropertiesInternal + + { + /// Gets or sets the AzStackHCICluster FQDN name. + string ClusterName { get; set; } + /// Gets or sets the AzStackHCICluster resource name. + string ResourceName { get; set; } + /// Gets or sets the Storage account name. + string StorageAccountName { get; set; } + /// Gets or sets the list of AzStackHCICluster Storage Container. + System.Collections.Generic.List StorageContainer { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.json.cs new file mode 100644 index 00000000000..86f77dcaf18 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciClusterProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// AzStackHCI cluster properties. + public partial class AzStackHciClusterProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal AzStackHciClusterProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_clusterName = If( json?.PropertyT("clusterName"), out var __jsonClusterName) ? (string)__jsonClusterName : (string)_clusterName;} + {_resourceName = If( json?.PropertyT("resourceName"), out var __jsonResourceName) ? (string)__jsonResourceName : (string)_resourceName;} + {_storageAccountName = If( json?.PropertyT("storageAccountName"), out var __jsonStorageAccountName) ? (string)__jsonStorageAccountName : (string)_storageAccountName;} + {_storageContainer = If( json?.PropertyT("storageContainers"), out var __jsonStorageContainers) ? If( __jsonStorageContainers as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IStorageContainerProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.StorageContainerProperties.FromJson(__u) )) ))() : null : _storageContainer;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new AzStackHciClusterProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._clusterName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._clusterName.ToString()) : null, "clusterName" ,container.Add ); + AddIf( null != (((object)this._resourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceName.ToString()) : null, "resourceName" ,container.Add ); + AddIf( null != (((object)this._storageAccountName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageAccountName.ToString()) : null, "storageAccountName" ,container.Add ); + if (null != this._storageContainer) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._storageContainer ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("storageContainers",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..bce0f09b25e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.PowerShell.cs @@ -0,0 +1,255 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// AzStackHCI fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(AzStackHciFabricModelCustomPropertiesTypeConverter))] + public partial class AzStackHciFabricModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AzStackHciFabricModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Cluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).Cluster = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties) content.GetValueForProperty("Cluster",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).Cluster, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AzStackHciClusterPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzStackHciSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).AzStackHciSiteId = (string) content.GetValueForProperty("AzStackHciSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).AzStackHciSiteId, global::System.Convert.ToString); + } + if (content.Contains("ApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ApplianceName = (System.Collections.Generic.List) content.GetValueForProperty("ApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ApplianceName, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("FabricResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricResourceId = (string) content.GetValueForProperty("FabricResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricResourceId, global::System.Convert.ToString); + } + if (content.Contains("FabricContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricContainerId = (string) content.GetValueForProperty("FabricContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricContainerId, global::System.Convert.ToString); + } + if (content.Contains("MigrationSolutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationSolutionId = (string) content.GetValueForProperty("MigrationSolutionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationSolutionId, global::System.Convert.ToString); + } + if (content.Contains("MigrationHubUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationHubUri = (string) content.GetValueForProperty("MigrationHubUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationHubUri, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("ClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterName, global::System.Convert.ToString); + } + if (content.Contains("ClusterResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterResourceName = (string) content.GetValueForProperty("ClusterResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterResourceName, global::System.Convert.ToString); + } + if (content.Contains("ClusterStorageAccountName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageAccountName = (string) content.GetValueForProperty("ClusterStorageAccountName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageAccountName, global::System.Convert.ToString); + } + if (content.Contains("ClusterStorageContainer")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageContainer = (System.Collections.Generic.List) content.GetValueForProperty("ClusterStorageContainer",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageContainer, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.StorageContainerPropertiesTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AzStackHciFabricModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Cluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).Cluster = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties) content.GetValueForProperty("Cluster",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).Cluster, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AzStackHciClusterPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzStackHciSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).AzStackHciSiteId = (string) content.GetValueForProperty("AzStackHciSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).AzStackHciSiteId, global::System.Convert.ToString); + } + if (content.Contains("ApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ApplianceName = (System.Collections.Generic.List) content.GetValueForProperty("ApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ApplianceName, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("FabricResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricResourceId = (string) content.GetValueForProperty("FabricResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricResourceId, global::System.Convert.ToString); + } + if (content.Contains("FabricContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricContainerId = (string) content.GetValueForProperty("FabricContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).FabricContainerId, global::System.Convert.ToString); + } + if (content.Contains("MigrationSolutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationSolutionId = (string) content.GetValueForProperty("MigrationSolutionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationSolutionId, global::System.Convert.ToString); + } + if (content.Contains("MigrationHubUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationHubUri = (string) content.GetValueForProperty("MigrationHubUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).MigrationHubUri, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("ClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterName, global::System.Convert.ToString); + } + if (content.Contains("ClusterResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterResourceName = (string) content.GetValueForProperty("ClusterResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterResourceName, global::System.Convert.ToString); + } + if (content.Contains("ClusterStorageAccountName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageAccountName = (string) content.GetValueForProperty("ClusterStorageAccountName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageAccountName, global::System.Convert.ToString); + } + if (content.Contains("ClusterStorageContainer")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageContainer = (System.Collections.Generic.List) content.GetValueForProperty("ClusterStorageContainer",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal)this).ClusterStorageContainer, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.StorageContainerPropertiesTypeConverter.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.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AzStackHciFabricModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AzStackHciFabricModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// AzStackHCI fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(AzStackHciFabricModelCustomPropertiesTypeConverter))] + public partial interface IAzStackHciFabricModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..de09987f53e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AzStackHciFabricModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AzStackHciFabricModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AzStackHciFabricModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AzStackHciFabricModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.cs new file mode 100644 index 00000000000..a428c154142 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// AzStackHCI fabric model custom properties. + public partial class AzStackHciFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties __fabricModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties(); + + /// Backing field for property. + private System.Collections.Generic.List _applianceName; + + /// Gets or sets the Appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ApplianceName { get => this._applianceName; } + + /// Backing field for property. + private string _azStackHciSiteId; + + /// Gets or sets the ARM Id of the AzStackHCI site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AzStackHciSiteId { get => this._azStackHciSiteId; set => this._azStackHciSiteId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties _cluster; + + /// AzStackHCI cluster properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties Cluster { get => (this._cluster = this._cluster ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AzStackHciClusterProperties()); set => this._cluster = value; } + + /// Gets or sets the AzStackHCICluster FQDN name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ClusterName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).ClusterName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).ClusterName = value ; } + + /// Gets or sets the AzStackHCICluster resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ClusterResourceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).ResourceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).ResourceName = value ; } + + /// Gets or sets the Storage account name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ClusterStorageAccountName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).StorageAccountName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).StorageAccountName = value ; } + + /// Gets or sets the list of AzStackHCICluster Storage Container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List ClusterStorageContainer { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).StorageContainer; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterPropertiesInternal)Cluster).StorageContainer = value ; } + + /// Backing field for property. + private string _fabricContainerId; + + /// Gets or sets the fabric container Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricContainerId { get => this._fabricContainerId; } + + /// Backing field for property. + private string _fabricResourceId; + + /// Gets or sets the fabric resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricResourceId { get => this._fabricResourceId; } + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "AzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)__fabricModelCustomProperties).InstanceType = "AzStackHCI"; } + + /// Internal Acessors for ApplianceName + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal.ApplianceName { get => this._applianceName; set { {_applianceName = value;} } } + + /// Internal Acessors for Cluster + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal.Cluster { get => (this._cluster = this._cluster ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AzStackHciClusterProperties()); set { {_cluster = value;} } } + + /// Internal Acessors for FabricContainerId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal.FabricContainerId { get => this._fabricContainerId; set { {_fabricContainerId = value;} } } + + /// Internal Acessors for FabricResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal.FabricResourceId { get => this._fabricResourceId; set { {_fabricResourceId = value;} } } + + /// Internal Acessors for MigrationHubUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomPropertiesInternal.MigrationHubUri { get => this._migrationHubUri; set { {_migrationHubUri = value;} } } + + /// Backing field for property. + private string _migrationHubUri; + + /// Gets or sets the migration hub Uri. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrationHubUri { get => this._migrationHubUri; } + + /// Backing field for property. + private string _migrationSolutionId; + + /// Gets or sets the Migration solution ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrationSolutionId { get => this._migrationSolutionId; set => this._migrationSolutionId = value; } + + /// Creates an new instance. + public AzStackHciFabricModelCustomProperties() + { + this.__fabricModelCustomProperties.InstanceType = "AzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__fabricModelCustomProperties), __fabricModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__fabricModelCustomProperties), __fabricModelCustomProperties); + } + } + /// AzStackHCI fabric model custom properties. + public partial interface IAzStackHciFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties + { + /// Gets or sets the Appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Appliance name.", + SerializedName = @"applianceName", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List ApplianceName { get; } + /// Gets or sets the ARM Id of the AzStackHCI site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the AzStackHCI site.", + SerializedName = @"azStackHciSiteId", + PossibleTypes = new [] { typeof(string) })] + string AzStackHciSiteId { get; set; } + /// Gets or sets the AzStackHCICluster FQDN name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the AzStackHCICluster FQDN name.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + string ClusterName { get; set; } + /// Gets or sets the AzStackHCICluster resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the AzStackHCICluster resource name.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + string ClusterResourceName { get; set; } + /// Gets or sets the Storage account name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Storage account name.", + SerializedName = @"storageAccountName", + PossibleTypes = new [] { typeof(string) })] + string ClusterStorageAccountName { get; set; } + /// Gets or sets the list of AzStackHCICluster Storage Container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of AzStackHCICluster Storage Container.", + SerializedName = @"storageContainers", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties) })] + System.Collections.Generic.List ClusterStorageContainer { get; set; } + /// Gets or sets the fabric container Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric container Id.", + SerializedName = @"fabricContainerId", + PossibleTypes = new [] { typeof(string) })] + string FabricContainerId { get; } + /// Gets or sets the fabric resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric resource Id.", + SerializedName = @"fabricResourceId", + PossibleTypes = new [] { typeof(string) })] + string FabricResourceId { get; } + /// Gets or sets the migration hub Uri. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the migration hub Uri.", + SerializedName = @"migrationHubUri", + PossibleTypes = new [] { typeof(string) })] + string MigrationHubUri { get; } + /// Gets or sets the Migration solution ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Migration solution ARM Id.", + SerializedName = @"migrationSolutionId", + PossibleTypes = new [] { typeof(string) })] + string MigrationSolutionId { get; set; } + + } + /// AzStackHCI fabric model custom properties. + internal partial interface IAzStackHciFabricModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal + { + /// Gets or sets the Appliance name. + System.Collections.Generic.List ApplianceName { get; set; } + /// Gets or sets the ARM Id of the AzStackHCI site. + string AzStackHciSiteId { get; set; } + /// AzStackHCI cluster properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciClusterProperties Cluster { get; set; } + /// Gets or sets the AzStackHCICluster FQDN name. + string ClusterName { get; set; } + /// Gets or sets the AzStackHCICluster resource name. + string ClusterResourceName { get; set; } + /// Gets or sets the Storage account name. + string ClusterStorageAccountName { get; set; } + /// Gets or sets the list of AzStackHCICluster Storage Container. + System.Collections.Generic.List ClusterStorageContainer { get; set; } + /// Gets or sets the fabric container Id. + string FabricContainerId { get; set; } + /// Gets or sets the fabric resource Id. + string FabricResourceId { get; set; } + /// Gets or sets the migration hub Uri. + string MigrationHubUri { get; set; } + /// Gets or sets the Migration solution ARM Id. + string MigrationSolutionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.json.cs new file mode 100644 index 00000000000..8ab3e0d345f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/AzStackHciFabricModelCustomProperties.json.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// AzStackHCI fabric model custom properties. + public partial class AzStackHciFabricModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal AzStackHciFabricModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __fabricModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties(json); + {_cluster = If( json?.PropertyT("cluster"), out var __jsonCluster) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AzStackHciClusterProperties.FromJson(__jsonCluster) : _cluster;} + {_azStackHciSiteId = If( json?.PropertyT("azStackHciSiteId"), out var __jsonAzStackHciSiteId) ? (string)__jsonAzStackHciSiteId : (string)_azStackHciSiteId;} + {_applianceName = If( json?.PropertyT("applianceName"), out var __jsonApplianceName) ? If( __jsonApplianceName as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _applianceName;} + {_fabricResourceId = If( json?.PropertyT("fabricResourceId"), out var __jsonFabricResourceId) ? (string)__jsonFabricResourceId : (string)_fabricResourceId;} + {_fabricContainerId = If( json?.PropertyT("fabricContainerId"), out var __jsonFabricContainerId) ? (string)__jsonFabricContainerId : (string)_fabricContainerId;} + {_migrationSolutionId = If( json?.PropertyT("migrationSolutionId"), out var __jsonMigrationSolutionId) ? (string)__jsonMigrationSolutionId : (string)_migrationSolutionId;} + {_migrationHubUri = If( json?.PropertyT("migrationHubUri"), out var __jsonMigrationHubUri) ? (string)__jsonMigrationHubUri : (string)_migrationHubUri;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAzStackHciFabricModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new AzStackHciFabricModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __fabricModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != this._cluster ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._cluster.ToJson(null,serializationMode) : null, "cluster" ,container.Add ); + AddIf( null != (((object)this._azStackHciSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._azStackHciSiteId.ToString()) : null, "azStackHciSiteId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._applianceName) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._applianceName ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("applianceName",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricResourceId.ToString()) : null, "fabricResourceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricContainerId.ToString()) : null, "fabricContainerId" ,container.Add ); + } + AddIf( null != (((object)this._migrationSolutionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrationSolutionId.ToString()) : null, "migrationSolutionId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._migrationHubUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrationHubUri.ToString()) : null, "migrationHubUri" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.PowerShell.cs new file mode 100644 index 00000000000..2bb19b8d4f5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Check name availability model. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityModelTypeConverter))] + public partial class CheckNameAvailabilityModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CheckNameAvailabilityModel(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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)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 CheckNameAvailabilityModel(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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CheckNameAvailabilityModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CheckNameAvailabilityModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Check name availability model. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityModelTypeConverter))] + public partial interface ICheckNameAvailabilityModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.TypeConverter.cs new file mode 100644 index 00000000000..87f52ce1d4c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CheckNameAvailabilityModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CheckNameAvailabilityModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CheckNameAvailabilityModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CheckNameAvailabilityModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.cs new file mode 100644 index 00000000000..1a9df7c939c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Check name availability model. + public partial class CheckNameAvailabilityModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModelInternal + { + + /// Backing field for property. + private string _name; + + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public CheckNameAvailabilityModel() + { + + } + } + /// Check name availability model. + public partial interface ICheckNameAvailabilityModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the resource name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; set; } + + } + /// Check name availability model. + internal partial interface ICheckNameAvailabilityModelInternal + + { + /// Gets or sets the resource name. + string Name { get; set; } + /// Gets or sets the resource type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.json.cs new file mode 100644 index 00000000000..54e166c0219 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Check name availability model. + public partial class CheckNameAvailabilityModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal CheckNameAvailabilityModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new CheckNameAvailabilityModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.PowerShell.cs new file mode 100644 index 00000000000..f841384dd23 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.PowerShell.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Check name availability response model. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityResponseModelTypeConverter))] + public partial class CheckNameAvailabilityResponseModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 CheckNameAvailabilityResponseModel(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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)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 CheckNameAvailabilityResponseModel(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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal)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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CheckNameAvailabilityResponseModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CheckNameAvailabilityResponseModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Check name availability response model. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityResponseModelTypeConverter))] + public partial interface ICheckNameAvailabilityResponseModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.TypeConverter.cs new file mode 100644 index 00000000000..765afc5bb96 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CheckNameAvailabilityResponseModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CheckNameAvailabilityResponseModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CheckNameAvailabilityResponseModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CheckNameAvailabilityResponseModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.cs new file mode 100644 index 00000000000..a6fa2ec4290 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Check name availability response model. + public partial class CheckNameAvailabilityResponseModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModelInternal + { + + /// Backing field for property. + private string _message; + + /// Gets or sets the message for resource name unavailability. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Backing field for property. + private bool? _nameAvailable; + + /// Gets or sets a value indicating whether resource name is available or not. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? NameAvailable { get => this._nameAvailable; set => this._nameAvailable = value; } + + /// Backing field for property. + private string _reason; + + /// Gets or sets the reason for resource name unavailability. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Reason { get => this._reason; set => this._reason = value; } + + /// Creates an new instance. + public CheckNameAvailabilityResponseModel() + { + + } + } + /// Check name availability response model. + public partial interface ICheckNameAvailabilityResponseModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the message for resource name unavailability. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the message for resource name unavailability.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + /// Gets or sets a value indicating whether resource name is available or not. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether resource name is available or not.", + SerializedName = @"nameAvailable", + PossibleTypes = new [] { typeof(bool) })] + bool? NameAvailable { get; set; } + /// Gets or sets the reason for resource name unavailability. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the reason for resource name unavailability.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + string Reason { get; set; } + + } + /// Check name availability response model. + internal partial interface ICheckNameAvailabilityResponseModelInternal + + { + /// Gets or sets the message for resource name unavailability. + string Message { get; set; } + /// Gets or sets a value indicating whether resource name is available or not. + bool? NameAvailable { get; set; } + /// Gets or sets the reason for resource name unavailability. + string Reason { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.json.cs new file mode 100644 index 00000000000..9e5e8d1f231 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/CheckNameAvailabilityResponseModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Check name availability response model. + public partial class CheckNameAvailabilityResponseModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal CheckNameAvailabilityResponseModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new CheckNameAvailabilityResponseModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._nameAvailable ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._nameAvailable) : null, "nameAvailable" ,container.Add ); + AddIf( null != (((object)this._reason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._reason.ToString()) : null, "reason" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.PowerShell.cs new file mode 100644 index 00000000000..440d5c187fc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.PowerShell.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Private endpoint connection details at member level. + [System.ComponentModel.TypeConverter(typeof(ConnectionDetailsTypeConverter))] + public partial class ConnectionDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ConnectionDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("PrivateIPAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).PrivateIPAddress = (string) content.GetValueForProperty("PrivateIPAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).PrivateIPAddress, global::System.Convert.ToString); + } + if (content.Contains("LinkIdentifier")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).LinkIdentifier = (string) content.GetValueForProperty("LinkIdentifier",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).LinkIdentifier, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("MemberName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).MemberName = (string) content.GetValueForProperty("MemberName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).MemberName, 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 ConnectionDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("PrivateIPAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).PrivateIPAddress = (string) content.GetValueForProperty("PrivateIPAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).PrivateIPAddress, global::System.Convert.ToString); + } + if (content.Contains("LinkIdentifier")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).LinkIdentifier = (string) content.GetValueForProperty("LinkIdentifier",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).LinkIdentifier, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("MemberName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).MemberName = (string) content.GetValueForProperty("MemberName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal)this).MemberName, 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.RecoveryServicesDataReplication.Models.IConnectionDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectionDetails(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectionDetails(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Private endpoint connection details at member level. + [System.ComponentModel.TypeConverter(typeof(ConnectionDetailsTypeConverter))] + public partial interface IConnectionDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.TypeConverter.cs new file mode 100644 index 00000000000..ef243ec6527 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectionDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IConnectionDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectionDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectionDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectionDetails.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.cs new file mode 100644 index 00000000000..08149ad89e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Private endpoint connection details at member level. + public partial class ConnectionDetails : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetailsInternal + { + + /// Backing field for property. + private string _groupId; + + /// Gets or sets group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string GroupId { get => this._groupId; set => this._groupId = value; } + + /// Backing field for property. + private string _id; + + /// Gets or sets id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _linkIdentifier; + + /// Gets or sets link identifier. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string LinkIdentifier { get => this._linkIdentifier; set => this._linkIdentifier = value; } + + /// Backing field for property. + private string _memberName; + + /// Gets or sets member name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MemberName { get => this._memberName; set => this._memberName = value; } + + /// Backing field for property. + private string _privateIPAddress; + + /// Gets or sets private IP address. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PrivateIPAddress { get => this._privateIPAddress; set => this._privateIPAddress = value; } + + /// Creates an new instance. + public ConnectionDetails() + { + + } + } + /// Private endpoint connection details at member level. + public partial interface IConnectionDetails : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets group id.", + SerializedName = @"groupId", + PossibleTypes = new [] { typeof(string) })] + string GroupId { get; set; } + /// Gets or sets id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Gets or sets link identifier. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets link identifier.", + SerializedName = @"linkIdentifier", + PossibleTypes = new [] { typeof(string) })] + string LinkIdentifier { get; set; } + /// Gets or sets member name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets member name.", + SerializedName = @"memberName", + PossibleTypes = new [] { typeof(string) })] + string MemberName { get; set; } + /// Gets or sets private IP address. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets private IP address.", + SerializedName = @"privateIpAddress", + PossibleTypes = new [] { typeof(string) })] + string PrivateIPAddress { get; set; } + + } + /// Private endpoint connection details at member level. + internal partial interface IConnectionDetailsInternal + + { + /// Gets or sets group id. + string GroupId { get; set; } + /// Gets or sets id. + string Id { get; set; } + /// Gets or sets link identifier. + string LinkIdentifier { get; set; } + /// Gets or sets member name. + string MemberName { get; set; } + /// Gets or sets private IP address. + string PrivateIPAddress { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.json.cs new file mode 100644 index 00000000000..f57e6023c8c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ConnectionDetails.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Private endpoint connection details at member level. + public partial class ConnectionDetails + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectionDetails(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_privateIPAddress = If( json?.PropertyT("privateIpAddress"), out var __jsonPrivateIPAddress) ? (string)__jsonPrivateIPAddress : (string)_privateIPAddress;} + {_linkIdentifier = If( json?.PropertyT("linkIdentifier"), out var __jsonLinkIdentifier) ? (string)__jsonLinkIdentifier : (string)_linkIdentifier;} + {_groupId = If( json?.PropertyT("groupId"), out var __jsonGroupId) ? (string)__jsonGroupId : (string)_groupId;} + {_memberName = If( json?.PropertyT("memberName"), out var __jsonMemberName) ? (string)__jsonMemberName : (string)_memberName;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ConnectionDetails(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._privateIPAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._privateIPAddress.ToString()) : null, "privateIpAddress" ,container.Add ); + AddIf( null != (((object)this._linkIdentifier)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._linkIdentifier.ToString()) : null, "linkIdentifier" ,container.Add ); + AddIf( null != (((object)this._groupId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._groupId.ToString()) : null, "groupId" ,container.Add ); + AddIf( null != (((object)this._memberName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._memberName.ToString()) : null, "memberName" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.PowerShell.cs new file mode 100644 index 00000000000..01dfdd2c783 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Deployment preflight model. + [System.ComponentModel.TypeConverter(typeof(DeploymentPreflightModelTypeConverter))] + public partial class DeploymentPreflightModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 DeploymentPreflightModel(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModelInternal)this).Resource = (System.Collections.Generic.List) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModelInternal)this).Resource, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightResourceTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal DeploymentPreflightModel(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModelInternal)this).Resource = (System.Collections.Generic.List) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModelInternal)this).Resource, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightResourceTypeConverter.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DeploymentPreflightModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DeploymentPreflightModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Deployment preflight model. + [System.ComponentModel.TypeConverter(typeof(DeploymentPreflightModelTypeConverter))] + public partial interface IDeploymentPreflightModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.TypeConverter.cs new file mode 100644 index 00000000000..cf666d5bfd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DeploymentPreflightModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DeploymentPreflightModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DeploymentPreflightModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DeploymentPreflightModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.cs new file mode 100644 index 00000000000..dca934007bc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Deployment preflight model. + public partial class DeploymentPreflightModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModelInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _resource; + + /// Gets or sets the list of resources. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public DeploymentPreflightModel() + { + + } + } + /// Deployment preflight model. + public partial interface IDeploymentPreflightModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the list of resources. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of resources.", + SerializedName = @"resources", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource) })] + System.Collections.Generic.List Resource { get; set; } + + } + /// Deployment preflight model. + internal partial interface IDeploymentPreflightModelInternal + + { + /// Gets or sets the list of resources. + System.Collections.Generic.List Resource { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.json.cs new file mode 100644 index 00000000000..13770622fb5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Deployment preflight model. + public partial class DeploymentPreflightModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal DeploymentPreflightModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_resource = If( json?.PropertyT("resources"), out var __jsonResources) ? If( __jsonResources as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightResource.FromJson(__u) )) ))() : null : _resource;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new DeploymentPreflightModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._resource) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._resource ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("resources",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.PowerShell.cs new file mode 100644 index 00000000000..888bf5fb060 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.PowerShell.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Deployment preflight resource. + [System.ComponentModel.TypeConverter(typeof(DeploymentPreflightResourceTypeConverter))] + public partial class DeploymentPreflightResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 DeploymentPreflightResource(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.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ApiVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).ApiVersion = (string) content.GetValueForProperty("ApiVersion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).ApiVersion, global::System.Convert.ToString); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal DeploymentPreflightResource(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.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ApiVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).ApiVersion = (string) content.GetValueForProperty("ApiVersion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).ApiVersion, global::System.Convert.ToString); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AnyTypeConverter.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DeploymentPreflightResource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DeploymentPreflightResource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Deployment preflight resource. + [System.ComponentModel.TypeConverter(typeof(DeploymentPreflightResourceTypeConverter))] + public partial interface IDeploymentPreflightResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.TypeConverter.cs new file mode 100644 index 00000000000..55999c73ebe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DeploymentPreflightResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DeploymentPreflightResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DeploymentPreflightResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DeploymentPreflightResource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.cs new file mode 100644 index 00000000000..540bc6ded71 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Deployment preflight resource. + public partial class DeploymentPreflightResource : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResourceInternal + { + + /// Backing field for property. + private string _apiVersion; + + /// Gets or sets the Api version. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ApiVersion { get => this._apiVersion; set => this._apiVersion = value; } + + /// Backing field for property. + private string _location; + + /// Gets or sets the location of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private string _name; + + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny _property; + + /// Gets or sets the properties of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Any()); set => this._property = value; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public DeploymentPreflightResource() + { + + } + } + /// Deployment preflight resource. + public partial interface IDeploymentPreflightResource : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the Api version. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Api version.", + SerializedName = @"apiVersion", + PossibleTypes = new [] { typeof(string) })] + string ApiVersion { get; set; } + /// Gets or sets the location of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Gets or sets the location of the resource.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the resource name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// Gets or sets the properties of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the properties of the resource.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny Property { get; set; } + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; set; } + + } + /// Deployment preflight resource. + internal partial interface IDeploymentPreflightResourceInternal + + { + /// Gets or sets the Api version. + string ApiVersion { get; set; } + /// Gets or sets the location of the resource. + string Location { get; set; } + /// Gets or sets the resource name. + string Name { get; set; } + /// Gets or sets the properties of the resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny Property { get; set; } + /// Gets or sets the resource type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.json.cs new file mode 100644 index 00000000000..63f88888c2b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DeploymentPreflightResource.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Deployment preflight resource. + public partial class DeploymentPreflightResource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal DeploymentPreflightResource(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + {_apiVersion = If( json?.PropertyT("apiVersion"), out var __jsonApiVersion) ? (string)__jsonApiVersion : (string)_apiVersion;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Any.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new DeploymentPreflightResource(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AddIf( null != (((object)this._apiVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._apiVersion.ToString()) : null, "apiVersion" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.PowerShell.cs new file mode 100644 index 00000000000..8713ce439cc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Disk controller. + [System.ComponentModel.TypeConverter(typeof(DiskControllerInputsTypeConverter))] + public partial class DiskControllerInputs + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IDiskControllerInputs DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DiskControllerInputs(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DiskControllerInputs(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DiskControllerInputs(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ControllerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerName = (string) content.GetValueForProperty("ControllerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerName, global::System.Convert.ToString); + } + if (content.Contains("ControllerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerId = (int) content.GetValueForProperty("ControllerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ControllerLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerLocation = (int) content.GetValueForProperty("ControllerLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerLocation, (__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 DiskControllerInputs(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ControllerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerName = (string) content.GetValueForProperty("ControllerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerName, global::System.Convert.ToString); + } + if (content.Contains("ControllerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerId = (int) content.GetValueForProperty("ControllerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ControllerLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerLocation = (int) content.GetValueForProperty("ControllerLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)this).ControllerLocation, (__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.RecoveryServicesDataReplication.Models.IDiskControllerInputs FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Disk controller. + [System.ComponentModel.TypeConverter(typeof(DiskControllerInputsTypeConverter))] + public partial interface IDiskControllerInputs + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.TypeConverter.cs new file mode 100644 index 00000000000..c8acde7755b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DiskControllerInputsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IDiskControllerInputs ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DiskControllerInputs.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DiskControllerInputs.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DiskControllerInputs.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.cs new file mode 100644 index 00000000000..11beab94d29 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Disk controller. + public partial class DiskControllerInputs : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal + { + + /// Backing field for property. + private int _controllerId; + + /// Gets or sets the controller ID. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int ControllerId { get => this._controllerId; set => this._controllerId = value; } + + /// Backing field for property. + private int _controllerLocation; + + /// Gets or sets the controller Location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int ControllerLocation { get => this._controllerLocation; set => this._controllerLocation = value; } + + /// Backing field for property. + private string _controllerName; + + /// Gets or sets the controller name (IDE,SCSI). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ControllerName { get => this._controllerName; set => this._controllerName = value; } + + /// Creates an new instance. + public DiskControllerInputs() + { + + } + } + /// Disk controller. + public partial interface IDiskControllerInputs : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the controller ID. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller ID.", + SerializedName = @"controllerId", + PossibleTypes = new [] { typeof(int) })] + int ControllerId { get; set; } + /// Gets or sets the controller Location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller Location.", + SerializedName = @"controllerLocation", + PossibleTypes = new [] { typeof(int) })] + int ControllerLocation { get; set; } + /// Gets or sets the controller name (IDE,SCSI). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller name (IDE,SCSI).", + SerializedName = @"controllerName", + PossibleTypes = new [] { typeof(string) })] + string ControllerName { get; set; } + + } + /// Disk controller. + internal partial interface IDiskControllerInputsInternal + + { + /// Gets or sets the controller ID. + int ControllerId { get; set; } + /// Gets or sets the controller Location. + int ControllerLocation { get; set; } + /// Gets or sets the controller name (IDE,SCSI). + string ControllerName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.json.cs new file mode 100644 index 00000000000..54f801fa4c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/DiskControllerInputs.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Disk controller. + public partial class DiskControllerInputs + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal DiskControllerInputs(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_controllerName = If( json?.PropertyT("controllerName"), out var __jsonControllerName) ? (string)__jsonControllerName : (string)_controllerName;} + {_controllerId = If( json?.PropertyT("controllerId"), out var __jsonControllerId) ? (int)__jsonControllerId : _controllerId;} + {_controllerLocation = If( json?.PropertyT("controllerLocation"), out var __jsonControllerLocation) ? (int)__jsonControllerLocation : _controllerLocation;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new DiskControllerInputs(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._controllerName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._controllerName.ToString()) : null, "controllerName" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._controllerId), "controllerId" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._controllerLocation), "controllerLocation" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.PowerShell.cs new file mode 100644 index 00000000000..c52e77a5b39 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.PowerShell.cs @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Email configuration model. + [System.ComponentModel.TypeConverter(typeof(EmailConfigurationModelTypeConverter))] + public partial class EmailConfigurationModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EmailConfigurationModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EmailConfigurationModel(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EmailConfigurationModel(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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("SendToOwner")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).SendToOwner = (bool?) content.GetValueForProperty("SendToOwner",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).SendToOwner, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CustomEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).CustomEmailAddress = (System.Collections.Generic.List) content.GetValueForProperty("CustomEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).CustomEmailAddress, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("Locale")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Locale = (string) content.GetValueForProperty("Locale",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Locale, 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 EmailConfigurationModel(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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("SendToOwner")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).SendToOwner = (bool?) content.GetValueForProperty("SendToOwner",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).SendToOwner, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CustomEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).CustomEmailAddress = (System.Collections.Generic.List) content.GetValueForProperty("CustomEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).CustomEmailAddress, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("Locale")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Locale = (string) content.GetValueForProperty("Locale",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal)this).Locale, 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Email configuration model. + [System.ComponentModel.TypeConverter(typeof(EmailConfigurationModelTypeConverter))] + public partial interface IEmailConfigurationModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.TypeConverter.cs new file mode 100644 index 00000000000..d77709849fa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EmailConfigurationModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EmailConfigurationModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EmailConfigurationModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EmailConfigurationModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.cs new file mode 100644 index 00000000000..87a9fbe9f86 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.cs @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Email configuration model. + public partial class EmailConfigurationModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Gets or sets the custom email address for sending emails. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List CustomEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).CustomEmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).CustomEmailAddress = value ?? null /* arrayOf */; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Gets or sets the locale for the email notification. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Locale { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).Locale; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).Locale = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the email configuration. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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); } + + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public bool? SendToOwner { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).SendToOwner; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)Property).SendToOwner = value ?? default(bool); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public EmailConfigurationModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Email configuration model. + public partial interface IEmailConfigurationModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets the custom email address for sending emails. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the custom email address for sending emails.", + SerializedName = @"customEmailAddresses", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List CustomEmailAddress { get; set; } + /// Gets or sets the locale for the email notification. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the locale for the email notification.", + SerializedName = @"locale", + PossibleTypes = new [] { typeof(string) })] + string Locale { get; set; } + /// Gets or sets the provisioning state of the email configuration. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the email configuration.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether to send email to subscription administrator.", + SerializedName = @"sendToOwners", + PossibleTypes = new [] { typeof(bool) })] + bool? SendToOwner { get; set; } + + } + /// Email configuration model. + internal partial interface IEmailConfigurationModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Gets or sets the custom email address for sending emails. + System.Collections.Generic.List CustomEmailAddress { get; set; } + /// Gets or sets the locale for the email notification. + string Locale { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the email configuration. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + bool? SendToOwner { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.json.cs new file mode 100644 index 00000000000..cacfe3c016c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Email configuration model. + public partial class EmailConfigurationModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EmailConfigurationModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new EmailConfigurationModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.PowerShell.cs new file mode 100644 index 00000000000..7f5416a415d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a EmailConfigurationModel list operation. + [System.ComponentModel.TypeConverter(typeof(EmailConfigurationModelListResultTypeConverter))] + public partial class EmailConfigurationModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EmailConfigurationModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EmailConfigurationModelListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EmailConfigurationModelListResult(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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)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 EmailConfigurationModelListResult(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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal)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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 EmailConfigurationModel list operation. + [System.ComponentModel.TypeConverter(typeof(EmailConfigurationModelListResultTypeConverter))] + public partial interface IEmailConfigurationModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..bb717c0fcee --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EmailConfigurationModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EmailConfigurationModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EmailConfigurationModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EmailConfigurationModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.cs new file mode 100644 index 00000000000..2d4dd269f57 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a EmailConfigurationModel list operation. + public partial class EmailConfigurationModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The EmailConfigurationModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public EmailConfigurationModelListResult() + { + + } + } + /// The response of a EmailConfigurationModel list operation. + public partial interface IEmailConfigurationModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EmailConfigurationModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The EmailConfigurationModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a EmailConfigurationModel list operation. + internal partial interface IEmailConfigurationModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The EmailConfigurationModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.json.cs new file mode 100644 index 00000000000..279984972df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a EmailConfigurationModel list operation. + public partial class EmailConfigurationModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EmailConfigurationModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new EmailConfigurationModelListResult(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.PowerShell.cs new file mode 100644 index 00000000000..a3e19020501 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.PowerShell.cs @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Email configuration model properties. + [System.ComponentModel.TypeConverter(typeof(EmailConfigurationModelPropertiesTypeConverter))] + public partial class EmailConfigurationModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EmailConfigurationModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EmailConfigurationModelProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EmailConfigurationModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SendToOwner")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).SendToOwner = (bool) content.GetValueForProperty("SendToOwner",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).SendToOwner, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CustomEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).CustomEmailAddress = (System.Collections.Generic.List) content.GetValueForProperty("CustomEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).CustomEmailAddress, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("Locale")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).Locale = (string) content.GetValueForProperty("Locale",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).Locale, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)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 EmailConfigurationModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SendToOwner")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).SendToOwner = (bool) content.GetValueForProperty("SendToOwner",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).SendToOwner, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CustomEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).CustomEmailAddress = (System.Collections.Generic.List) content.GetValueForProperty("CustomEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).CustomEmailAddress, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("Locale")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).Locale = (string) content.GetValueForProperty("Locale",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).Locale, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal)this).ProvisioningState, 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Email configuration model properties. + [System.ComponentModel.TypeConverter(typeof(EmailConfigurationModelPropertiesTypeConverter))] + public partial interface IEmailConfigurationModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..58961472de4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EmailConfigurationModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EmailConfigurationModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EmailConfigurationModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EmailConfigurationModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.cs new file mode 100644 index 00000000000..3980145fcef --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Email configuration model properties. + public partial class EmailConfigurationModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _customEmailAddress; + + /// Gets or sets the custom email address for sending emails. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List CustomEmailAddress { get => this._customEmailAddress; set => this._customEmailAddress = value; } + + /// Backing field for property. + private string _locale; + + /// Gets or sets the locale for the email notification. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Locale { get => this._locale; set => this._locale = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the email configuration. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private bool _sendToOwner; + + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool SendToOwner { get => this._sendToOwner; set => this._sendToOwner = value; } + + /// Creates an new instance. + public EmailConfigurationModelProperties() + { + + } + } + /// Email configuration model properties. + public partial interface IEmailConfigurationModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the custom email address for sending emails. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the custom email address for sending emails.", + SerializedName = @"customEmailAddresses", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List CustomEmailAddress { get; set; } + /// Gets or sets the locale for the email notification. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the locale for the email notification.", + SerializedName = @"locale", + PossibleTypes = new [] { typeof(string) })] + string Locale { get; set; } + /// Gets or sets the provisioning state of the email configuration. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the email configuration.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether to send email to subscription administrator.", + SerializedName = @"sendToOwners", + PossibleTypes = new [] { typeof(bool) })] + bool SendToOwner { get; set; } + + } + /// Email configuration model properties. + internal partial interface IEmailConfigurationModelPropertiesInternal + + { + /// Gets or sets the custom email address for sending emails. + System.Collections.Generic.List CustomEmailAddress { get; set; } + /// Gets or sets the locale for the email notification. + string Locale { get; set; } + /// Gets or sets the provisioning state of the email configuration. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + bool SendToOwner { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.json.cs new file mode 100644 index 00000000000..bed4aaf2f86 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EmailConfigurationModelProperties.json.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Email configuration model properties. + public partial class EmailConfigurationModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EmailConfigurationModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_sendToOwner = If( json?.PropertyT("sendToOwners"), out var __jsonSendToOwners) ? (bool)__jsonSendToOwners : _sendToOwner;} + {_customEmailAddress = If( json?.PropertyT("customEmailAddresses"), out var __jsonCustomEmailAddresses) ? If( __jsonCustomEmailAddresses as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _customEmailAddress;} + {_locale = If( json?.PropertyT("locale"), out var __jsonLocale) ? (string)__jsonLocale : (string)_locale;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new EmailConfigurationModelProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean(this._sendToOwner), "sendToOwners" ,container.Add ); + if (null != this._customEmailAddress) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._customEmailAddress ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("customEmailAddresses",__w); + } + AddIf( null != (((object)this._locale)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._locale.ToString()) : null, "locale" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..8c0bd99b92d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..71329dec577 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..257fe28eb66 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..21568f18419 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..2799932fa97 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..ddfb4de2073 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..97a5d949a08 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..7ee686eae89 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.PowerShell.cs new file mode 100644 index 00000000000..7ac401120c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Error model. + [System.ComponentModel.TypeConverter(typeof(ErrorModelTypeConverter))] + public partial class ErrorModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IErrorModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorModel(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorModel(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.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("CreationTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).CreationTime = (global::System.DateTime?) content.GetValueForProperty("CreationTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).CreationTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Caus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Caus = (string) content.GetValueForProperty("Caus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Caus, global::System.Convert.ToString); + } + if (content.Contains("Recommendation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Recommendation = (string) content.GetValueForProperty("Recommendation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Recommendation, 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 ErrorModel(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.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("CreationTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).CreationTime = (global::System.DateTime?) content.GetValueForProperty("CreationTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).CreationTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Caus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Caus = (string) content.GetValueForProperty("Caus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Caus, global::System.Convert.ToString); + } + if (content.Contains("Recommendation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Recommendation = (string) content.GetValueForProperty("Recommendation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal)this).Recommendation, 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.RecoveryServicesDataReplication.Models.IErrorModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Error model. + [System.ComponentModel.TypeConverter(typeof(ErrorModelTypeConverter))] + public partial interface IErrorModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.TypeConverter.cs new file mode 100644 index 00000000000..9723d5dd0e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IErrorModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.cs new file mode 100644 index 00000000000..49cc1eb7f9a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Error model. + public partial class ErrorModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal + { + + /// Backing field for property. + private string _caus; + + /// Gets or sets the possible causes of error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Caus { get => this._caus; } + + /// Backing field for property. + private string _code; + + /// Gets or sets the error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private global::System.DateTime? _creationTime; + + /// Gets or sets the creation time of error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? CreationTime { get => this._creationTime; } + + /// Backing field for property. + private string _message; + + /// Gets or sets the error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Caus + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.Caus { get => this._caus; set { {_caus = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for CreationTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.CreationTime { get => this._creationTime; set { {_creationTime = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Recommendation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.Recommendation { get => this._recommendation; set { {_recommendation = value;} } } + + /// Internal Acessors for Severity + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.Severity { get => this._severity; set { {_severity = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModelInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _recommendation; + + /// Gets or sets the recommended action to resolve error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Recommendation { get => this._recommendation; } + + /// Backing field for property. + private string _severity; + + /// Gets or sets the error severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Severity { get => this._severity; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the error type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ErrorModel() + { + + } + } + /// Error model. + public partial interface IErrorModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the possible causes of error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the possible causes of error.", + SerializedName = @"causes", + PossibleTypes = new [] { typeof(string) })] + string Caus { get; } + /// Gets or sets the error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Gets or sets the creation time of error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the creation time of error.", + SerializedName = @"creationTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreationTime { get; } + /// Gets or sets the error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// Gets or sets the recommended action to resolve error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the recommended action to resolve error.", + SerializedName = @"recommendation", + PossibleTypes = new [] { typeof(string) })] + string Recommendation { get; } + /// Gets or sets the error severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error severity.", + SerializedName = @"severity", + PossibleTypes = new [] { typeof(string) })] + string Severity { get; } + /// Gets or sets the error type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Error model. + internal partial interface IErrorModelInternal + + { + /// Gets or sets the possible causes of error. + string Caus { get; set; } + /// Gets or sets the error code. + string Code { get; set; } + /// Gets or sets the creation time of error. + global::System.DateTime? CreationTime { get; set; } + /// Gets or sets the error message. + string Message { get; set; } + /// Gets or sets the recommended action to resolve error. + string Recommendation { get; set; } + /// Gets or sets the error severity. + string Severity { get; set; } + /// Gets or sets the error type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.json.cs new file mode 100644 index 00000000000..1cd2ab67a68 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorModel.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Error model. + public partial class ErrorModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_severity = If( json?.PropertyT("severity"), out var __jsonSeverity) ? (string)__jsonSeverity : (string)_severity;} + {_creationTime = If( json?.PropertyT("creationTime"), out var __jsonCreationTime) ? global::System.DateTime.TryParse((string)__jsonCreationTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreationTimeValue) ? __jsonCreationTimeValue : _creationTime : _creationTime;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)_message;} + {_caus = If( json?.PropertyT("causes"), out var __jsonCauses) ? (string)__jsonCauses : (string)_caus;} + {_recommendation = If( json?.PropertyT("recommendation"), out var __jsonRecommendation) ? (string)__jsonRecommendation : (string)_recommendation;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ErrorModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._severity)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._severity.ToString()) : null, "severity" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._creationTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._creationTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "creationTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._caus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._caus.ToString()) : null, "causes" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._recommendation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recommendation.ToString()) : null, "recommendation" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..e2bb10fde79 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..02aebf95544 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..cd93e9ce412 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Message = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorDetailInternal)Error).Target = value ?? null; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..d2fc39ba76b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/EventModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.PowerShell.cs new file mode 100644 index 00000000000..24294707c7e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.PowerShell.cs @@ -0,0 +1,338 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Event model. + [System.ComponentModel.TypeConverter(typeof(EventModelTypeConverter))] + public partial class EventModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEventModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EventModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EventModel(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EventModel(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.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceType = (string) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceType, global::System.Convert.ToString); + } + if (content.Contains("ResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceName, global::System.Convert.ToString); + } + if (content.Contains("EventType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventType = (string) content.GetValueForProperty("EventType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventType, global::System.Convert.ToString); + } + if (content.Contains("EventName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventName = (string) content.GetValueForProperty("EventName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventName, global::System.Convert.ToString); + } + if (content.Contains("TimeOfOccurrence")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).TimeOfOccurrence = (global::System.DateTime?) content.GetValueForProperty("TimeOfOccurrence",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).TimeOfOccurrence, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomPropertyInstanceType, 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 EventModel(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.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceType = (string) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceType, global::System.Convert.ToString); + } + if (content.Contains("ResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).ResourceName, global::System.Convert.ToString); + } + if (content.Contains("EventType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventType = (string) content.GetValueForProperty("EventType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventType, global::System.Convert.ToString); + } + if (content.Contains("EventName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventName = (string) content.GetValueForProperty("EventName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).EventName, global::System.Convert.ToString); + } + if (content.Contains("TimeOfOccurrence")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).TimeOfOccurrence = (global::System.DateTime?) content.GetValueForProperty("TimeOfOccurrence",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).TimeOfOccurrence, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IEventModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Event model. + [System.ComponentModel.TypeConverter(typeof(EventModelTypeConverter))] + public partial interface IEventModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.TypeConverter.cs new file mode 100644 index 00000000000..3c497ea6acb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EventModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEventModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EventModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EventModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EventModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EventModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.cs new file mode 100644 index 00000000000..d337fb6e526 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.cs @@ -0,0 +1,371 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Event model. + public partial class EventModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Gets or sets the event correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CorrelationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CorrelationId; } + + /// Event model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Gets or sets the event description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).Description; } + + /// Gets or sets the event name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string EventName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).EventName; } + + /// Gets or sets the event type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string EventType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).EventType; } + + /// Gets or sets the errors associated with this event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).HealthError; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for CorrelationId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.CorrelationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CorrelationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CorrelationId = value ?? null; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).Description = value ?? null; } + + /// Internal Acessors for EventName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.EventName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).EventName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).EventName = value ?? null; } + + /// Internal Acessors for EventType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.EventType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).EventType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).EventType = value ?? null; } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).HealthError; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).HealthError = value ?? null /* arrayOf */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ResourceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.ResourceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ResourceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ResourceName = value ?? null; } + + /// Internal Acessors for ResourceType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.ResourceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ResourceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ResourceType = value ?? null; } + + /// Internal Acessors for Severity + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.Severity { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).Severity; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).Severity = value ?? null; } + + /// Internal Acessors for TimeOfOccurrence + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelInternal.TimeOfOccurrence { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).TimeOfOccurrence; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).TimeOfOccurrence = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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); } + + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ResourceName; } + + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).ResourceType; } + + /// Gets or sets the event severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Severity { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).Severity; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// Gets or sets the time at which the event occurred at source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? TimeOfOccurrence { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)Property).TimeOfOccurrence; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public EventModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Event model. + public partial interface IEventModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets the event correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event correlation Id.", + SerializedName = @"correlationId", + PossibleTypes = new [] { typeof(string) })] + string CorrelationId { get; } + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for EventModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the event description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// Gets or sets the event name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event name.", + SerializedName = @"eventName", + PossibleTypes = new [] { typeof(string) })] + string EventName { get; } + /// Gets or sets the event type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event type.", + SerializedName = @"eventType", + PossibleTypes = new [] { typeof(string) })] + string EventType { get; } + /// Gets or sets the errors associated with this event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the errors associated with this event.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the provisioning state of the event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the event.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource name.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + string ResourceName { get; } + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource type.", + SerializedName = @"resourceType", + PossibleTypes = new [] { typeof(string) })] + string ResourceType { get; } + /// Gets or sets the event severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event severity.", + SerializedName = @"severity", + PossibleTypes = new [] { typeof(string) })] + string Severity { get; } + /// Gets or sets the time at which the event occurred at source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the time at which the event occurred at source.", + SerializedName = @"timeOfOccurrence", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TimeOfOccurrence { get; } + + } + /// Event model. + internal partial interface IEventModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Gets or sets the event correlation Id. + string CorrelationId { get; set; } + /// Event model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for EventModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the event description. + string Description { get; set; } + /// Gets or sets the event name. + string EventName { get; set; } + /// Gets or sets the event type. + string EventType { get; set; } + /// Gets or sets the errors associated with this event. + System.Collections.Generic.List HealthError { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the event. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the resource name. + string ResourceName { get; set; } + /// Gets or sets the resource type. + string ResourceType { get; set; } + /// Gets or sets the event severity. + string Severity { get; set; } + /// Gets or sets the time at which the event occurred at source. + global::System.DateTime? TimeOfOccurrence { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.json.cs new file mode 100644 index 00000000000..4a0a2f053f9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Event model. + public partial class EventModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EventModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new EventModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..418330cac1c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Event model custom properties. + [System.ComponentModel.TypeConverter(typeof(EventModelCustomPropertiesTypeConverter))] + public partial class EventModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEventModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EventModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EventModelCustomProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EventModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType, 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 EventModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.Models.IEventModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Event model custom properties. + [System.ComponentModel.TypeConverter(typeof(EventModelCustomPropertiesTypeConverter))] + public partial interface IEventModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..5f2b0b2b9fc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EventModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEventModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EventModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EventModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EventModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.cs new file mode 100644 index 00000000000..fe5dfa72681 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Event model custom properties. + public partial class EventModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public EventModelCustomProperties() + { + + } + } + /// Event model custom properties. + public partial interface IEventModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for EventModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Event model custom properties. + internal partial interface IEventModelCustomPropertiesInternal + + { + /// Discriminator property for EventModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.json.cs new file mode 100644 index 00000000000..e930ad7d442 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Event model custom properties. + public partial class EventModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EventModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties interface + /// is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHcieventModelCustomProperties(json); + } + case "VMwareToAzStackHCI": + { + return new VMwareToAzStackHcieventModelCustomProperties(json); + } + } + return new EventModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.PowerShell.cs new file mode 100644 index 00000000000..73c32cdea49 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a EventModel list operation. + [System.ComponentModel.TypeConverter(typeof(EventModelListResultTypeConverter))] + public partial class EventModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEventModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EventModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EventModelListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EventModelListResult(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.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)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 EventModelListResult(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.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal)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.RecoveryServicesDataReplication.Models.IEventModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 EventModel list operation. + [System.ComponentModel.TypeConverter(typeof(EventModelListResultTypeConverter))] + public partial interface IEventModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..d458aa3dd78 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EventModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEventModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EventModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EventModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EventModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.cs new file mode 100644 index 00000000000..6bcee3762ba --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a EventModel list operation. + public partial class EventModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The EventModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public EventModelListResult() + { + + } + } + /// The response of a EventModel list operation. + public partial interface IEventModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 EventModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The EventModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a EventModel list operation. + internal partial interface IEventModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The EventModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.json.cs new file mode 100644 index 00000000000..e845a35d645 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a EventModel list operation. + public partial class EventModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EventModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModel.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.RecoveryServicesDataReplication.Models.IEventModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new EventModelListResult(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.PowerShell.cs new file mode 100644 index 00000000000..c906b34bafa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Event model properties. + [System.ComponentModel.TypeConverter(typeof(EventModelPropertiesTypeConverter))] + public partial class EventModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IEventModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new EventModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new EventModelProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal EventModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceType = (string) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceType, global::System.Convert.ToString); + } + if (content.Contains("ResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceName, global::System.Convert.ToString); + } + if (content.Contains("EventType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventType = (string) content.GetValueForProperty("EventType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventType, global::System.Convert.ToString); + } + if (content.Contains("EventName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventName = (string) content.GetValueForProperty("EventName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventName, global::System.Convert.ToString); + } + if (content.Contains("TimeOfOccurrence")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).TimeOfOccurrence = (global::System.DateTime?) content.GetValueForProperty("TimeOfOccurrence",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).TimeOfOccurrence, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomPropertyInstanceType, 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 EventModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceType = (string) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceType, global::System.Convert.ToString); + } + if (content.Contains("ResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ResourceName, global::System.Convert.ToString); + } + if (content.Contains("EventType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventType = (string) content.GetValueForProperty("EventType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventType, global::System.Convert.ToString); + } + if (content.Contains("EventName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventName = (string) content.GetValueForProperty("EventName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).EventName, global::System.Convert.ToString); + } + if (content.Contains("TimeOfOccurrence")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).TimeOfOccurrence = (global::System.DateTime?) content.GetValueForProperty("TimeOfOccurrence",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).TimeOfOccurrence, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IEventModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Event model properties. + [System.ComponentModel.TypeConverter(typeof(EventModelPropertiesTypeConverter))] + public partial interface IEventModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..de2dded55da --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class EventModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IEventModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return EventModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return EventModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return EventModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.cs new file mode 100644 index 00000000000..d2973b85a4c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.cs @@ -0,0 +1,293 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Event model properties. + public partial class EventModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal + { + + /// Backing field for property. + private string _correlationId; + + /// Gets or sets the event correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string CorrelationId { get => this._correlationId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties _customProperty; + + /// Event model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Backing field for property. + private string _description; + + /// Gets or sets the event description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Backing field for property. + private string _eventName; + + /// Gets or sets the event name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EventName { get => this._eventName; } + + /// Backing field for property. + private string _eventType; + + /// Gets or sets the event type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EventType { get => this._eventType; } + + /// Backing field for property. + private System.Collections.Generic.List _healthError; + + /// Gets or sets the errors associated with this event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List HealthError { get => this._healthError; } + + /// Internal Acessors for CorrelationId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.CorrelationId { get => this._correlationId; set { {_correlationId = value;} } } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for EventName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.EventName { get => this._eventName; set { {_eventName = value;} } } + + /// Internal Acessors for EventType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.EventType { get => this._eventType; set { {_eventType = value;} } } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.HealthError { get => this._healthError; set { {_healthError = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for ResourceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.ResourceName { get => this._resourceName; set { {_resourceName = value;} } } + + /// Internal Acessors for ResourceType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.ResourceType { get => this._resourceType; set { {_resourceType = value;} } } + + /// Internal Acessors for Severity + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.Severity { get => this._severity; set { {_severity = value;} } } + + /// Internal Acessors for TimeOfOccurrence + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelPropertiesInternal.TimeOfOccurrence { get => this._timeOfOccurrence; set { {_timeOfOccurrence = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _resourceName; + + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceName { get => this._resourceName; } + + /// Backing field for property. + private string _resourceType; + + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceType { get => this._resourceType; } + + /// Backing field for property. + private string _severity; + + /// Gets or sets the event severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Severity { get => this._severity; } + + /// Backing field for property. + private global::System.DateTime? _timeOfOccurrence; + + /// Gets or sets the time at which the event occurred at source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? TimeOfOccurrence { get => this._timeOfOccurrence; } + + /// Creates an new instance. + public EventModelProperties() + { + + } + } + /// Event model properties. + public partial interface IEventModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the event correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event correlation Id.", + SerializedName = @"correlationId", + PossibleTypes = new [] { typeof(string) })] + string CorrelationId { get; } + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for EventModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the event description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// Gets or sets the event name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event name.", + SerializedName = @"eventName", + PossibleTypes = new [] { typeof(string) })] + string EventName { get; } + /// Gets or sets the event type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event type.", + SerializedName = @"eventType", + PossibleTypes = new [] { typeof(string) })] + string EventType { get; } + /// Gets or sets the errors associated with this event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the errors associated with this event.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the provisioning state of the event. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the event.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the resource name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource name.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + string ResourceName { get; } + /// Gets or sets the resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource type.", + SerializedName = @"resourceType", + PossibleTypes = new [] { typeof(string) })] + string ResourceType { get; } + /// Gets or sets the event severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the event severity.", + SerializedName = @"severity", + PossibleTypes = new [] { typeof(string) })] + string Severity { get; } + /// Gets or sets the time at which the event occurred at source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the time at which the event occurred at source.", + SerializedName = @"timeOfOccurrence", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? TimeOfOccurrence { get; } + + } + /// Event model properties. + internal partial interface IEventModelPropertiesInternal + + { + /// Gets or sets the event correlation Id. + string CorrelationId { get; set; } + /// Event model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for EventModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the event description. + string Description { get; set; } + /// Gets or sets the event name. + string EventName { get; set; } + /// Gets or sets the event type. + string EventType { get; set; } + /// Gets or sets the errors associated with this event. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets the provisioning state of the event. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the resource name. + string ResourceName { get; set; } + /// Gets or sets the resource type. + string ResourceType { get; set; } + /// Gets or sets the event severity. + string Severity { get; set; } + /// Gets or sets the time at which the event occurred at source. + global::System.DateTime? TimeOfOccurrence { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.json.cs new file mode 100644 index 00000000000..02032cf1ef8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/EventModelProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Event model properties. + public partial class EventModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal EventModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_resourceType = If( json?.PropertyT("resourceType"), out var __jsonResourceType) ? (string)__jsonResourceType : (string)_resourceType;} + {_resourceName = If( json?.PropertyT("resourceName"), out var __jsonResourceName) ? (string)__jsonResourceName : (string)_resourceName;} + {_eventType = If( json?.PropertyT("eventType"), out var __jsonEventType) ? (string)__jsonEventType : (string)_eventType;} + {_eventName = If( json?.PropertyT("eventName"), out var __jsonEventName) ? (string)__jsonEventName : (string)_eventName;} + {_timeOfOccurrence = If( json?.PropertyT("timeOfOccurrence"), out var __jsonTimeOfOccurrence) ? global::System.DateTime.TryParse((string)__jsonTimeOfOccurrence, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonTimeOfOccurrenceValue) ? __jsonTimeOfOccurrenceValue : _timeOfOccurrence : _timeOfOccurrence;} + {_severity = If( json?.PropertyT("severity"), out var __jsonSeverity) ? (string)__jsonSeverity : (string)_severity;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_correlationId = If( json?.PropertyT("correlationId"), out var __jsonCorrelationId) ? (string)__jsonCorrelationId : (string)_correlationId;} + {_healthError = If( json?.PropertyT("healthErrors"), out var __jsonHealthErrors) ? If( __jsonHealthErrors as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHealthErrorModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModel.FromJson(__u) )) ))() : null : _healthError;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new EventModelProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceType.ToString()) : null, "resourceType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceName.ToString()) : null, "resourceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eventType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._eventType.ToString()) : null, "eventType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eventName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._eventName.ToString()) : null, "eventName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._timeOfOccurrence ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._timeOfOccurrence?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "timeOfOccurrence" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._severity)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._severity.ToString()) : null, "severity" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._correlationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._correlationId.ToString()) : null, "correlationId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._healthError) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._healthError ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("healthErrors",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.PowerShell.cs new file mode 100644 index 00000000000..a4670c21ab6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.PowerShell.cs @@ -0,0 +1,420 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric agent model. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelTypeConverter))] + public partial class FabricAgentModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricAgentModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricAgentModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricAgentModel(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricAgentModel(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.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("AuthenticationIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceAccessIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("ResourceAccessIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("MachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineId = (string) content.GetValueForProperty("MachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineId, global::System.Convert.ToString); + } + if (content.Contains("MachineName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineName = (string) content.GetValueForProperty("MachineName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineName, global::System.Convert.ToString); + } + if (content.Contains("IsResponsive")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).IsResponsive = (bool?) content.GetValueForProperty("IsResponsive",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).IsResponsive, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastHeartbeat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).LastHeartbeat = (global::System.DateTime?) content.GetValueForProperty("LastHeartbeat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).LastHeartbeat, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("VersionNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).VersionNumber = (string) content.GetValueForProperty("VersionNumber",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).VersionNumber, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("AuthenticationIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityTenantId = (string) content.GetValueForProperty("AuthenticationIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityApplicationId = (string) content.GetValueForProperty("AuthenticationIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityObjectId = (string) content.GetValueForProperty("AuthenticationIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAudience = (string) content.GetValueForProperty("AuthenticationIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAadAuthority = (string) content.GetValueForProperty("AuthenticationIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityTenantId = (string) content.GetValueForProperty("ResourceAccessIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityApplicationId = (string) content.GetValueForProperty("ResourceAccessIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityObjectId = (string) content.GetValueForProperty("ResourceAccessIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAudience = (string) content.GetValueForProperty("ResourceAccessIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAadAuthority = (string) content.GetValueForProperty("ResourceAccessIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomPropertyInstanceType, 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 FabricAgentModel(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.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("AuthenticationIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceAccessIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("ResourceAccessIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("MachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineId = (string) content.GetValueForProperty("MachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineId, global::System.Convert.ToString); + } + if (content.Contains("MachineName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineName = (string) content.GetValueForProperty("MachineName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).MachineName, global::System.Convert.ToString); + } + if (content.Contains("IsResponsive")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).IsResponsive = (bool?) content.GetValueForProperty("IsResponsive",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).IsResponsive, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastHeartbeat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).LastHeartbeat = (global::System.DateTime?) content.GetValueForProperty("LastHeartbeat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).LastHeartbeat, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("VersionNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).VersionNumber = (string) content.GetValueForProperty("VersionNumber",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).VersionNumber, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("AuthenticationIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityTenantId = (string) content.GetValueForProperty("AuthenticationIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityApplicationId = (string) content.GetValueForProperty("AuthenticationIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityObjectId = (string) content.GetValueForProperty("AuthenticationIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAudience = (string) content.GetValueForProperty("AuthenticationIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAadAuthority = (string) content.GetValueForProperty("AuthenticationIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).AuthenticationIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityTenantId = (string) content.GetValueForProperty("ResourceAccessIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityApplicationId = (string) content.GetValueForProperty("ResourceAccessIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityObjectId = (string) content.GetValueForProperty("ResourceAccessIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAudience = (string) content.GetValueForProperty("ResourceAccessIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAadAuthority = (string) content.GetValueForProperty("ResourceAccessIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).ResourceAccessIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IFabricAgentModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric agent model. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelTypeConverter))] + public partial interface IFabricAgentModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.TypeConverter.cs new file mode 100644 index 00000000000..47192356bfc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricAgentModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricAgentModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricAgentModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricAgentModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricAgentModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.cs new file mode 100644 index 00000000000..6310fc9395b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric agent model. + public partial class FabricAgentModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityAadAuthority { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityAadAuthority; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityAadAuthority = value ?? null; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityApplicationId = value ?? null; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityAudience { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityAudience; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityAudience = value ?? null; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityObjectId = value ?? null; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityTenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentityTenantId = value ?? null; } + + /// Gets or sets the fabric agent correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CorrelationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CorrelationId; } + + /// Fabric agent model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).HealthError; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Gets or sets a value indicating whether the fabric agent is responsive. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public bool? IsResponsive { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).IsResponsive; } + + /// Gets or sets the time when last heartbeat was sent by the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastHeartbeat { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).LastHeartbeat; } + + /// Gets or sets the machine Id where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MachineId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).MachineId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).MachineId = value ?? null; } + + /// Gets or sets the machine name where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MachineName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).MachineName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).MachineName = value ?? null; } + + /// Internal Acessors for AuthenticationIdentity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.AuthenticationIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).AuthenticationIdentity = value ?? null /* model class */; } + + /// Internal Acessors for CorrelationId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.CorrelationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CorrelationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CorrelationId = value ?? null; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).HealthError; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).HealthError = value ?? null /* arrayOf */; } + + /// Internal Acessors for IsResponsive + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.IsResponsive { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).IsResponsive; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).IsResponsive = value ?? default(bool); } + + /// Internal Acessors for LastHeartbeat + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.LastHeartbeat { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).LastHeartbeat; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).LastHeartbeat = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ResourceAccessIdentity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.ResourceAccessIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentity = value ?? null /* model class */; } + + /// Internal Acessors for VersionNumber + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelInternal.VersionNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).VersionNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).VersionNumber = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ProvisioningState; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityAadAuthority { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityAadAuthority; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityAadAuthority = value ?? null; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityApplicationId = value ?? null; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityAudience { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityAudience; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityAudience = value ?? null; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityObjectId = value ?? null; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityTenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).ResourceAccessIdentityTenantId = value ?? null; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Gets or sets the fabric agent version. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string VersionNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)Property).VersionNumber; } + + /// Creates an new instance. + public FabricAgentModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Fabric agent model. + public partial interface IFabricAgentModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityTenantId { get; set; } + /// Gets or sets the fabric agent correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric agent correlation Id.", + SerializedName = @"correlationId", + PossibleTypes = new [] { typeof(string) })] + string CorrelationId { get; } + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets a value indicating whether the fabric agent is responsive. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether the fabric agent is responsive.", + SerializedName = @"isResponsive", + PossibleTypes = new [] { typeof(bool) })] + bool? IsResponsive { get; } + /// Gets or sets the time when last heartbeat was sent by the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the time when last heartbeat was sent by the fabric agent.", + SerializedName = @"lastHeartbeat", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastHeartbeat { get; } + /// Gets or sets the machine Id where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the machine Id where fabric agent is running.", + SerializedName = @"machineId", + PossibleTypes = new [] { typeof(string) })] + string MachineId { get; set; } + /// Gets or sets the machine name where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the machine name where fabric agent is running.", + SerializedName = @"machineName", + PossibleTypes = new [] { typeof(string) })] + string MachineName { get; set; } + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric agent.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityTenantId { get; set; } + /// Gets or sets the fabric agent version. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric agent version.", + SerializedName = @"versionNumber", + PossibleTypes = new [] { typeof(string) })] + string VersionNumber { get; } + + } + /// Fabric agent model. + internal partial interface IFabricAgentModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Identity model. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel AuthenticationIdentity { get; set; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityTenantId { get; set; } + /// Gets or sets the fabric agent correlation Id. + string CorrelationId { get; set; } + /// Fabric agent model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for FabricAgentModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets a value indicating whether the fabric agent is responsive. + bool? IsResponsive { get; set; } + /// Gets or sets the time when last heartbeat was sent by the fabric agent. + global::System.DateTime? LastHeartbeat { get; set; } + /// Gets or sets the machine Id where fabric agent is running. + string MachineId { get; set; } + /// Gets or sets the machine name where fabric agent is running. + string MachineName { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the fabric agent. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Identity model. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel ResourceAccessIdentity { get; set; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityTenantId { get; set; } + /// Gets or sets the fabric agent version. + string VersionNumber { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.json.cs new file mode 100644 index 00000000000..2bfdd3b3e5e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric agent model. + public partial class FabricAgentModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricAgentModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricAgentModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..65fcfe89995 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric agent model custom properties. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelCustomPropertiesTypeConverter))] + public partial class FabricAgentModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricAgentModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricAgentModelCustomProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricAgentModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType, 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 FabricAgentModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric agent model custom properties. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelCustomPropertiesTypeConverter))] + public partial interface IFabricAgentModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..7d9318acbe3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricAgentModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricAgentModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricAgentModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricAgentModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.cs new file mode 100644 index 00000000000..b27979e24ad --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric agent model custom properties. + public partial class FabricAgentModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public FabricAgentModelCustomProperties() + { + + } + } + /// Fabric agent model custom properties. + public partial interface IFabricAgentModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Fabric agent model custom properties. + internal partial interface IFabricAgentModelCustomPropertiesInternal + + { + /// Discriminator property for FabricAgentModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.json.cs new file mode 100644 index 00000000000..f706fb14d33 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric agent model custom properties. + public partial class FabricAgentModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricAgentModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties + /// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the + /// payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "VMware": + { + return new VMwareFabricAgentModelCustomProperties(json); + } + } + return new FabricAgentModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.PowerShell.cs new file mode 100644 index 00000000000..61abfc4fde8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a FabricAgentModel list operation. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelListResultTypeConverter))] + public partial class FabricAgentModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricAgentModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricAgentModelListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricAgentModelListResult(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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)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 FabricAgentModelListResult(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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal)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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricAgentModel list operation. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelListResultTypeConverter))] + public partial interface IFabricAgentModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..ded108788a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricAgentModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricAgentModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricAgentModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricAgentModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.cs new file mode 100644 index 00000000000..190af1c1f0c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a FabricAgentModel list operation. + public partial class FabricAgentModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The FabricAgentModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public FabricAgentModelListResult() + { + + } + } + /// The response of a FabricAgentModel list operation. + public partial interface IFabricAgentModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricAgentModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The FabricAgentModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a FabricAgentModel list operation. + internal partial interface IFabricAgentModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The FabricAgentModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.json.cs new file mode 100644 index 00000000000..8dac2e41a75 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a FabricAgentModel list operation. + public partial class FabricAgentModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricAgentModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel.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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricAgentModelListResult(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.PowerShell.cs new file mode 100644 index 00000000000..9780d808546 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.PowerShell.cs @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric agent model properties. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelPropertiesTypeConverter))] + public partial class FabricAgentModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricAgentModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricAgentModelProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricAgentModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AuthenticationIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("AuthenticationIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceAccessIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("ResourceAccessIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("MachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineId = (string) content.GetValueForProperty("MachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineId, global::System.Convert.ToString); + } + if (content.Contains("MachineName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineName = (string) content.GetValueForProperty("MachineName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineName, global::System.Convert.ToString); + } + if (content.Contains("IsResponsive")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).IsResponsive = (bool?) content.GetValueForProperty("IsResponsive",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).IsResponsive, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastHeartbeat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).LastHeartbeat = (global::System.DateTime?) content.GetValueForProperty("LastHeartbeat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).LastHeartbeat, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("VersionNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).VersionNumber = (string) content.GetValueForProperty("VersionNumber",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).VersionNumber, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("AuthenticationIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityTenantId = (string) content.GetValueForProperty("AuthenticationIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityApplicationId = (string) content.GetValueForProperty("AuthenticationIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityObjectId = (string) content.GetValueForProperty("AuthenticationIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAudience = (string) content.GetValueForProperty("AuthenticationIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAadAuthority = (string) content.GetValueForProperty("AuthenticationIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityTenantId = (string) content.GetValueForProperty("ResourceAccessIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityApplicationId = (string) content.GetValueForProperty("ResourceAccessIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityObjectId = (string) content.GetValueForProperty("ResourceAccessIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAudience = (string) content.GetValueForProperty("ResourceAccessIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAadAuthority = (string) content.GetValueForProperty("ResourceAccessIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomPropertyInstanceType, 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 FabricAgentModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AuthenticationIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("AuthenticationIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("ResourceAccessIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("ResourceAccessIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("MachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineId = (string) content.GetValueForProperty("MachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineId, global::System.Convert.ToString); + } + if (content.Contains("MachineName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineName = (string) content.GetValueForProperty("MachineName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).MachineName, global::System.Convert.ToString); + } + if (content.Contains("IsResponsive")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).IsResponsive = (bool?) content.GetValueForProperty("IsResponsive",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).IsResponsive, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastHeartbeat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).LastHeartbeat = (global::System.DateTime?) content.GetValueForProperty("LastHeartbeat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).LastHeartbeat, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("VersionNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).VersionNumber = (string) content.GetValueForProperty("VersionNumber",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).VersionNumber, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("AuthenticationIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityTenantId = (string) content.GetValueForProperty("AuthenticationIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityApplicationId = (string) content.GetValueForProperty("AuthenticationIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityObjectId = (string) content.GetValueForProperty("AuthenticationIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAudience = (string) content.GetValueForProperty("AuthenticationIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("AuthenticationIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAadAuthority = (string) content.GetValueForProperty("AuthenticationIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).AuthenticationIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityTenantId = (string) content.GetValueForProperty("ResourceAccessIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityApplicationId = (string) content.GetValueForProperty("ResourceAccessIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityObjectId = (string) content.GetValueForProperty("ResourceAccessIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAudience = (string) content.GetValueForProperty("ResourceAccessIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("ResourceAccessIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAadAuthority = (string) content.GetValueForProperty("ResourceAccessIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).ResourceAccessIdentityAadAuthority, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric agent model properties. + [System.ComponentModel.TypeConverter(typeof(FabricAgentModelPropertiesTypeConverter))] + public partial interface IFabricAgentModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..17123d47b10 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricAgentModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricAgentModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricAgentModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricAgentModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.cs new file mode 100644 index 00000000000..c59665ba235 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric agent model properties. + public partial class FabricAgentModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel _authenticationIdentity; + + /// Identity model. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel AuthenticationIdentity { get => (this._authenticationIdentity = this._authenticationIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel()); set => this._authenticationIdentity = value; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityAadAuthority { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).AadAuthority; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).AadAuthority = value ; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).ApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).ApplicationId = value ; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityAudience { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).Audience; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).Audience = value ; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).ObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).ObjectId = value ; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AuthenticationIdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)AuthenticationIdentity).TenantId = value ; } + + /// Backing field for property. + private string _correlationId; + + /// Gets or sets the fabric agent correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string CorrelationId { get => this._correlationId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties _customProperty; + + /// Fabric agent model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Backing field for property. + private System.Collections.Generic.List _healthError; + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List HealthError { get => this._healthError; } + + /// Backing field for property. + private bool? _isResponsive; + + /// Gets or sets a value indicating whether the fabric agent is responsive. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsResponsive { get => this._isResponsive; } + + /// Backing field for property. + private global::System.DateTime? _lastHeartbeat; + + /// Gets or sets the time when last heartbeat was sent by the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastHeartbeat { get => this._lastHeartbeat; } + + /// Backing field for property. + private string _machineId; + + /// Gets or sets the machine Id where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MachineId { get => this._machineId; set => this._machineId = value; } + + /// Backing field for property. + private string _machineName; + + /// Gets or sets the machine name where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MachineName { get => this._machineName; set => this._machineName = value; } + + /// Internal Acessors for AuthenticationIdentity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.AuthenticationIdentity { get => (this._authenticationIdentity = this._authenticationIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel()); set { {_authenticationIdentity = value;} } } + + /// Internal Acessors for CorrelationId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.CorrelationId { get => this._correlationId; set { {_correlationId = value;} } } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.HealthError { get => this._healthError; set { {_healthError = value;} } } + + /// Internal Acessors for IsResponsive + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.IsResponsive { get => this._isResponsive; set { {_isResponsive = value;} } } + + /// Internal Acessors for LastHeartbeat + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.LastHeartbeat { get => this._lastHeartbeat; set { {_lastHeartbeat = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for ResourceAccessIdentity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.ResourceAccessIdentity { get => (this._resourceAccessIdentity = this._resourceAccessIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel()); set { {_resourceAccessIdentity = value;} } } + + /// Internal Acessors for VersionNumber + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelPropertiesInternal.VersionNumber { get => this._versionNumber; set { {_versionNumber = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel _resourceAccessIdentity; + + /// Identity model. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel ResourceAccessIdentity { get => (this._resourceAccessIdentity = this._resourceAccessIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel()); set => this._resourceAccessIdentity = value; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityAadAuthority { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).AadAuthority; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).AadAuthority = value ; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).ApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).ApplicationId = value ; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityAudience { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).Audience; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).Audience = value ; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).ObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).ObjectId = value ; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResourceAccessIdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)ResourceAccessIdentity).TenantId = value ; } + + /// Backing field for property. + private string _versionNumber; + + /// Gets or sets the fabric agent version. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VersionNumber { get => this._versionNumber; } + + /// Creates an new instance. + public FabricAgentModelProperties() + { + + } + } + /// Fabric agent model properties. + public partial interface IFabricAgentModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string AuthenticationIdentityTenantId { get; set; } + /// Gets or sets the fabric agent correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric agent correlation Id.", + SerializedName = @"correlationId", + PossibleTypes = new [] { typeof(string) })] + string CorrelationId { get; } + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets a value indicating whether the fabric agent is responsive. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether the fabric agent is responsive.", + SerializedName = @"isResponsive", + PossibleTypes = new [] { typeof(bool) })] + bool? IsResponsive { get; } + /// Gets or sets the time when last heartbeat was sent by the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the time when last heartbeat was sent by the fabric agent.", + SerializedName = @"lastHeartbeat", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastHeartbeat { get; } + /// Gets or sets the machine Id where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the machine Id where fabric agent is running.", + SerializedName = @"machineId", + PossibleTypes = new [] { typeof(string) })] + string MachineId { get; set; } + /// Gets or sets the machine name where fabric agent is running. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the machine name where fabric agent is running.", + SerializedName = @"machineName", + PossibleTypes = new [] { typeof(string) })] + string MachineName { get; set; } + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric agent.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string ResourceAccessIdentityTenantId { get; set; } + /// Gets or sets the fabric agent version. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric agent version.", + SerializedName = @"versionNumber", + PossibleTypes = new [] { typeof(string) })] + string VersionNumber { get; } + + } + /// Fabric agent model properties. + internal partial interface IFabricAgentModelPropertiesInternal + + { + /// Identity model. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel AuthenticationIdentity { get; set; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + string AuthenticationIdentityTenantId { get; set; } + /// Gets or sets the fabric agent correlation Id. + string CorrelationId { get; set; } + /// Fabric agent model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for FabricAgentModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets a value indicating whether the fabric agent is responsive. + bool? IsResponsive { get; set; } + /// Gets or sets the time when last heartbeat was sent by the fabric agent. + global::System.DateTime? LastHeartbeat { get; set; } + /// Gets or sets the machine Id where fabric agent is running. + string MachineId { get; set; } + /// Gets or sets the machine name where fabric agent is running. + string MachineName { get; set; } + /// Gets or sets the provisioning state of the fabric agent. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Identity model. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel ResourceAccessIdentity { get; set; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + string ResourceAccessIdentityTenantId { get; set; } + /// Gets or sets the fabric agent version. + string VersionNumber { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.json.cs new file mode 100644 index 00000000000..d85b961dcfd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricAgentModelProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric agent model properties. + public partial class FabricAgentModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricAgentModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_authenticationIdentity = If( json?.PropertyT("authenticationIdentity"), out var __jsonAuthenticationIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel.FromJson(__jsonAuthenticationIdentity) : _authenticationIdentity;} + {_resourceAccessIdentity = If( json?.PropertyT("resourceAccessIdentity"), out var __jsonResourceAccessIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel.FromJson(__jsonResourceAccessIdentity) : _resourceAccessIdentity;} + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_correlationId = If( json?.PropertyT("correlationId"), out var __jsonCorrelationId) ? (string)__jsonCorrelationId : (string)_correlationId;} + {_machineId = If( json?.PropertyT("machineId"), out var __jsonMachineId) ? (string)__jsonMachineId : (string)_machineId;} + {_machineName = If( json?.PropertyT("machineName"), out var __jsonMachineName) ? (string)__jsonMachineName : (string)_machineName;} + {_isResponsive = If( json?.PropertyT("isResponsive"), out var __jsonIsResponsive) ? (bool?)__jsonIsResponsive : _isResponsive;} + {_lastHeartbeat = If( json?.PropertyT("lastHeartbeat"), out var __jsonLastHeartbeat) ? global::System.DateTime.TryParse((string)__jsonLastHeartbeat, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastHeartbeatValue) ? __jsonLastHeartbeatValue : _lastHeartbeat : _lastHeartbeat;} + {_versionNumber = If( json?.PropertyT("versionNumber"), out var __jsonVersionNumber) ? (string)__jsonVersionNumber : (string)_versionNumber;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_healthError = If( json?.PropertyT("healthErrors"), out var __jsonHealthErrors) ? If( __jsonHealthErrors as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHealthErrorModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModel.FromJson(__u) )) ))() : null : _healthError;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricAgentModelProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._authenticationIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._authenticationIdentity.ToJson(null,serializationMode) : null, "authenticationIdentity" ,container.Add ); + AddIf( null != this._resourceAccessIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._resourceAccessIdentity.ToJson(null,serializationMode) : null, "resourceAccessIdentity" ,container.Add ); + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._correlationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._correlationId.ToString()) : null, "correlationId" ,container.Add ); + } + AddIf( null != (((object)this._machineId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._machineId.ToString()) : null, "machineId" ,container.Add ); + AddIf( null != (((object)this._machineName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._machineName.ToString()) : null, "machineName" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isResponsive ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isResponsive) : null, "isResponsive" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastHeartbeat ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastHeartbeat?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastHeartbeat" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._versionNumber)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._versionNumber.ToString()) : null, "versionNumber" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._healthError) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._healthError ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("healthErrors",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.PowerShell.cs new file mode 100644 index 00000000000..2d67cd4a012 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.PowerShell.cs @@ -0,0 +1,314 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric model. + [System.ComponentModel.TypeConverter(typeof(FabricModelTypeConverter))] + public partial class FabricModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricModel(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricModel(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.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ServiceEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceEndpoint = (string) content.GetValueForProperty("ServiceEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceEndpoint, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Health")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Health = (string) content.GetValueForProperty("Health",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Health, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomPropertyInstanceType, 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 FabricModel(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.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ServiceEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceEndpoint = (string) content.GetValueForProperty("ServiceEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceEndpoint, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Health")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Health = (string) content.GetValueForProperty("Health",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).Health, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IFabricModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric model. + [System.ComponentModel.TypeConverter(typeof(FabricModelTypeConverter))] + public partial interface IFabricModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.TypeConverter.cs new file mode 100644 index 00000000000..107c32b4cb6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.cs new file mode 100644 index 00000000000..1d4818b912d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.cs @@ -0,0 +1,281 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model. + public partial class FabricModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResource(); + + /// Fabric model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Gets or sets the fabric health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Health { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).Health; } + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).HealthError; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Health + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.Health { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).Health; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).Health = value ?? null; } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).HealthError; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).HealthError = value ?? null /* arrayOf */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ServiceEndpoint + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.ServiceEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceEndpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceEndpoint = value ?? null; } + + /// Internal Acessors for ServiceResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelInternal.ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceResourceId = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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); } + + /// Gets or sets the service endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ServiceEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceEndpoint; } + + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceResourceId; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public FabricModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Fabric model. + public partial interface IFabricModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResource + { + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric health.", + SerializedName = @"health", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string Health { get; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the provisioning state of the fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the service endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service endpoint.", + SerializedName = @"serviceEndpoint", + PossibleTypes = new [] { typeof(string) })] + string ServiceEndpoint { get; } + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service resource Id.", + SerializedName = @"serviceResourceId", + PossibleTypes = new [] { typeof(string) })] + string ServiceResourceId { get; } + + } + /// Fabric model. + internal partial interface IFabricModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal + { + /// Fabric model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for FabricModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric health. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string Health { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the fabric. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the service endpoint. + string ServiceEndpoint { get; set; } + /// Gets or sets the service resource Id. + string ServiceResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.json.cs new file mode 100644 index 00000000000..e29d8daba82 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model. + public partial class FabricModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..8a352639824 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(FabricModelCustomPropertiesTypeConverter))] + public partial class FabricModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricModelCustomProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, 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 FabricModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(FabricModelCustomPropertiesTypeConverter))] + public partial interface IFabricModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..cffd4360b64 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.cs new file mode 100644 index 00000000000..709cc56b838 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model custom properties. + public partial class FabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public FabricModelCustomProperties() + { + + } + } + /// Fabric model custom properties. + public partial interface IFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Fabric model custom properties. + internal partial interface IFabricModelCustomPropertiesInternal + + { + /// Discriminator property for FabricModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.json.cs new file mode 100644 index 00000000000..fe27c4a88e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelCustomProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model custom properties. + public partial class FabricModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties interface + /// is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "AzStackHCI": + { + return new AzStackHciFabricModelCustomProperties(json); + } + case "HyperVMigrate": + { + return new HyperVMigrateFabricModelCustomProperties(json); + } + case "VMwareMigrate": + { + return new VMwareMigrateFabricModelCustomProperties(json); + } + } + return new FabricModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.PowerShell.cs new file mode 100644 index 00000000000..a9bc2317534 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a FabricModel list operation. + [System.ComponentModel.TypeConverter(typeof(FabricModelListResultTypeConverter))] + public partial class FabricModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricModelListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricModelListResult(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.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)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 FabricModelListResult(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.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal)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.RecoveryServicesDataReplication.Models.IFabricModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 FabricModel list operation. + [System.ComponentModel.TypeConverter(typeof(FabricModelListResultTypeConverter))] + public partial interface IFabricModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..c1dc8b16f55 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.cs new file mode 100644 index 00000000000..7c771265d82 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a FabricModel list operation. + public partial class FabricModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The FabricModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public FabricModelListResult() + { + + } + } + /// The response of a FabricModel list operation. + public partial interface IFabricModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 FabricModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The FabricModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a FabricModel list operation. + internal partial interface IFabricModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The FabricModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.json.cs new file mode 100644 index 00000000000..b2f50bd3b27 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a FabricModel list operation. + public partial class FabricModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel.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.RecoveryServicesDataReplication.Models.IFabricModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricModelListResult(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.PowerShell.cs new file mode 100644 index 00000000000..886862b3c76 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.PowerShell.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric model properties. + [System.ComponentModel.TypeConverter(typeof(FabricModelPropertiesTypeConverter))] + public partial class FabricModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricModelProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceEndpoint = (string) content.GetValueForProperty("ServiceEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceEndpoint, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Health")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).Health = (string) content.GetValueForProperty("Health",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).Health, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomPropertyInstanceType, 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 FabricModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceEndpoint = (string) content.GetValueForProperty("ServiceEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceEndpoint, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Health")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).Health = (string) content.GetValueForProperty("Health",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).Health, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IFabricModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric model properties. + [System.ComponentModel.TypeConverter(typeof(FabricModelPropertiesTypeConverter))] + public partial interface IFabricModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..0991a121cae --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.cs new file mode 100644 index 00000000000..be25218d03b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model properties. + public partial class FabricModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties _customProperty; + + /// Fabric model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Backing field for property. + private string _health; + + /// Gets or sets the fabric health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Health { get => this._health; } + + /// Backing field for property. + private System.Collections.Generic.List _healthError; + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List HealthError { get => this._healthError; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for Health + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal.Health { get => this._health; set { {_health = value;} } } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal.HealthError { get => this._healthError; set { {_healthError = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for ServiceEndpoint + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal.ServiceEndpoint { get => this._serviceEndpoint; set { {_serviceEndpoint = value;} } } + + /// Internal Acessors for ServiceResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal.ServiceResourceId { get => this._serviceResourceId; set { {_serviceResourceId = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _serviceEndpoint; + + /// Gets or sets the service endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ServiceEndpoint { get => this._serviceEndpoint; } + + /// Backing field for property. + private string _serviceResourceId; + + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ServiceResourceId { get => this._serviceResourceId; } + + /// Creates an new instance. + public FabricModelProperties() + { + + } + } + /// Fabric model properties. + public partial interface IFabricModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric health.", + SerializedName = @"health", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string Health { get; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the provisioning state of the fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the service endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service endpoint.", + SerializedName = @"serviceEndpoint", + PossibleTypes = new [] { typeof(string) })] + string ServiceEndpoint { get; } + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service resource Id.", + SerializedName = @"serviceResourceId", + PossibleTypes = new [] { typeof(string) })] + string ServiceResourceId { get; } + + } + /// Fabric model properties. + internal partial interface IFabricModelPropertiesInternal + + { + /// Fabric model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for FabricModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric health. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string Health { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets the provisioning state of the fabric. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the service endpoint. + string ServiceEndpoint { get; set; } + /// Gets or sets the service resource Id. + string ServiceResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.json.cs new file mode 100644 index 00000000000..560bb401497 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model properties. + public partial class FabricModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_serviceEndpoint = If( json?.PropertyT("serviceEndpoint"), out var __jsonServiceEndpoint) ? (string)__jsonServiceEndpoint : (string)_serviceEndpoint;} + {_serviceResourceId = If( json?.PropertyT("serviceResourceId"), out var __jsonServiceResourceId) ? (string)__jsonServiceResourceId : (string)_serviceResourceId;} + {_health = If( json?.PropertyT("health"), out var __jsonHealth) ? (string)__jsonHealth : (string)_health;} + {_healthError = If( json?.PropertyT("healthErrors"), out var __jsonHealthErrors) ? If( __jsonHealthErrors as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHealthErrorModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModel.FromJson(__u) )) ))() : null : _healthError;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricModelProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._serviceEndpoint)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._serviceEndpoint.ToString()) : null, "serviceEndpoint" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._serviceResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._serviceResourceId.ToString()) : null, "serviceResourceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._health)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._health.ToString()) : null, "health" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._healthError) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._healthError ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("healthErrors",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.PowerShell.cs new file mode 100644 index 00000000000..7cb2819874a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.PowerShell.cs @@ -0,0 +1,308 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Fabric model update. + [System.ComponentModel.TypeConverter(typeof(FabricModelUpdateTypeConverter))] + public partial class FabricModelUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricModelUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricModelUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricModelUpdate(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricModelUpdate(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.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelUpdateTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ServiceEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceEndpoint = (string) content.GetValueForProperty("ServiceEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceEndpoint, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Health")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Health = (string) content.GetValueForProperty("Health",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Health, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)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.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)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("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomPropertyInstanceType, 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 FabricModelUpdate(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.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelUpdateTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ServiceEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceEndpoint = (string) content.GetValueForProperty("ServiceEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceEndpoint, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("Health")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Health = (string) content.GetValueForProperty("Health",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).Health, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)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.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)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("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.Models.IFabricModelUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Fabric model update. + [System.ComponentModel.TypeConverter(typeof(FabricModelUpdateTypeConverter))] + public partial interface IFabricModelUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.TypeConverter.cs new file mode 100644 index 00000000000..2dfd0322720 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricModelUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricModelUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricModelUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricModelUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricModelUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.cs new file mode 100644 index 00000000000..c0251e0af33 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model update. + public partial class FabricModelUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal + { + + /// Fabric model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Gets or sets the fabric health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string Health { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).Health; } + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).HealthError; } + + /// Backing field for property. + private string _id; + + /// Gets or sets the Id of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Health + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.Health { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).Health; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).Health = value ?? null; } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).HealthError; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).HealthError = value ?? null /* arrayOf */; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ServiceEndpoint + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.ServiceEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceEndpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceEndpoint = value ?? null; } + + /// Internal Acessors for ServiceResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceResourceId = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Gets or sets the name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties _property; + + /// Fabric model properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets or sets the service endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ServiceEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceEndpoint; } + + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelPropertiesInternal)Property).ServiceResourceId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData _systemData; + + /// Metadata pertaining to creation and last modification of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags _tag; + + /// Gets or sets the resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelUpdateTags()); set => this._tag = value; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public FabricModelUpdate() + { + + } + } + /// Fabric model update. + public partial interface IFabricModelUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric health.", + SerializedName = @"health", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string Health { get; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the Id of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Id of the resource.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Gets or sets the name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the name of the resource.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Gets or sets the provisioning state of the fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the service endpoint. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service endpoint.", + SerializedName = @"serviceEndpoint", + PossibleTypes = new [] { typeof(string) })] + string ServiceEndpoint { get; } + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service resource Id.", + SerializedName = @"serviceResourceId", + PossibleTypes = new [] { typeof(string) })] + string ServiceResourceId { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// Gets or sets the resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags Tag { get; set; } + /// Gets or sets the type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the type of the resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Fabric model update. + internal partial interface IFabricModelUpdateInternal + + { + /// Fabric model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for FabricModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric health. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string Health { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets the Id of the resource. + string Id { get; set; } + /// Gets or sets the name of the resource. + string Name { get; set; } + /// Fabric model properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the fabric. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the service endpoint. + string ServiceEndpoint { get; set; } + /// Gets or sets the service resource Id. + string ServiceResourceId { get; set; } + /// Metadata pertaining to creation and last modification of the resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// Gets or sets the resource tags. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags Tag { get; set; } + /// Gets or sets the type of the resource. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.json.cs new file mode 100644 index 00000000000..9f953eb6789 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdate.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Fabric model update. + public partial class FabricModelUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FabricModelUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.FabricModelProperties.FromJson(__jsonProperties) : _property;} + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelUpdateTags.FromJson(__jsonTags) : _tag;} + {_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); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricModelUpdate(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.PowerShell.cs new file mode 100644 index 00000000000..b08e59a48f5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.PowerShell.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Gets or sets the resource tags. + [System.ComponentModel.TypeConverter(typeof(FabricModelUpdateTagsTypeConverter))] + public partial class FabricModelUpdateTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FabricModelUpdateTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FabricModelUpdateTags(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FabricModelUpdateTags(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 FabricModelUpdateTags(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); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Gets or sets the resource tags. + [System.ComponentModel.TypeConverter(typeof(FabricModelUpdateTagsTypeConverter))] + public partial interface IFabricModelUpdateTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.TypeConverter.cs new file mode 100644 index 00000000000..52b8d747f8e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FabricModelUpdateTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FabricModelUpdateTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FabricModelUpdateTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FabricModelUpdateTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.cs new file mode 100644 index 00000000000..fdc490e86e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Gets or sets the resource tags. + public partial class FabricModelUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTagsInternal + { + + /// Creates an new instance. + public FabricModelUpdateTags() + { + + } + } + /// Gets or sets the resource tags. + public partial interface IFabricModelUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + + } + /// Gets or sets the resource tags. + internal partial interface IFabricModelUpdateTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.dictionary.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.dictionary.cs new file mode 100644 index 00000000000..ca221a12937 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + public partial class FabricModelUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.FabricModelUpdateTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.json.cs new file mode 100644 index 00000000000..b4cdc0e6940 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FabricModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Gets or sets the resource tags. + public partial class FabricModelUpdateTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + /// + internal FabricModelUpdateTags(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FabricModelUpdateTags(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..a36d8527202 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.PowerShell.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Failover job model custom properties. + [System.ComponentModel.TypeConverter(typeof(FailoverJobModelCustomPropertiesTypeConverter))] + public partial class FailoverJobModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FailoverJobModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FailoverJobModelCustomProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FailoverJobModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProtectedItemDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedItemDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FailoverProtectedItemPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, 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 FailoverJobModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProtectedItemDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedItemDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FailoverProtectedItemPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Failover job model custom properties. + [System.ComponentModel.TypeConverter(typeof(FailoverJobModelCustomPropertiesTypeConverter))] + public partial interface IFailoverJobModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..9796827fbb2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FailoverJobModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FailoverJobModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FailoverJobModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FailoverJobModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.cs new file mode 100644 index 00000000000..e036549d66f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Failover job model custom properties. + public partial class FailoverJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties __jobModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties(); + + /// Gets or sets any custom properties of the affected object. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails AffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail = value ?? null /* model class */; } + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription; } + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType; } + + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "FailoverJobDetails"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).InstanceType = "FailoverJobDetails"; } + + /// Internal Acessors for ProtectedItemDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomPropertiesInternal.ProtectedItemDetail { get => this._protectedItemDetail; set { {_protectedItemDetail = value;} } } + + /// Internal Acessors for AffectedObjectDetail + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail = value ?? null /* model class */; } + + /// Internal Acessors for AffectedObjectDetailDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType = value ?? null; } + + /// Backing field for property. + private System.Collections.Generic.List _protectedItemDetail; + + /// Gets or sets the failed over protected item details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ProtectedItemDetail { get => this._protectedItemDetail; } + + /// Creates an new instance. + public FailoverJobModelCustomProperties() + { + this.__jobModelCustomProperties.InstanceType = "FailoverJobDetails"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__jobModelCustomProperties), __jobModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__jobModelCustomProperties), __jobModelCustomProperties); + } + } + /// Failover job model custom properties. + public partial interface IFailoverJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties + { + /// Gets or sets the failed over protected item details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the failed over protected item details.", + SerializedName = @"protectedItemDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties) })] + System.Collections.Generic.List ProtectedItemDetail { get; } + + } + /// Failover job model custom properties. + internal partial interface IFailoverJobModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal + { + /// Gets or sets the failed over protected item details. + System.Collections.Generic.List ProtectedItemDetail { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.json.cs new file mode 100644 index 00000000000..b432f4d5e41 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Failover job model custom properties. + public partial class FailoverJobModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FailoverJobModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __jobModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties(json); + {_protectedItemDetail = If( json?.PropertyT("protectedItemDetails"), out var __jsonProtectedItemDetails) ? If( __jsonProtectedItemDetails as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FailoverProtectedItemProperties.FromJson(__u) )) ))() : null : _protectedItemDetail;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverJobModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FailoverJobModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __jobModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._protectedItemDetail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._protectedItemDetail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("protectedItemDetails",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.PowerShell.cs new file mode 100644 index 00000000000..7fae47abed4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.PowerShell.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Failover properties of the protected item. + [System.ComponentModel.TypeConverter(typeof(FailoverProtectedItemPropertiesTypeConverter))] + public partial class FailoverProtectedItemProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FailoverProtectedItemProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FailoverProtectedItemProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FailoverProtectedItemProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProtectedItemName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).ProtectedItemName = (string) content.GetValueForProperty("ProtectedItemName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).ProtectedItemName, global::System.Convert.ToString); + } + if (content.Contains("VMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).VMName = (string) content.GetValueForProperty("VMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).VMName, global::System.Convert.ToString); + } + if (content.Contains("TestVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).TestVMName = (string) content.GetValueForProperty("TestVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).TestVMName, global::System.Convert.ToString); + } + if (content.Contains("RecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointId = (string) content.GetValueForProperty("RecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("RecoveryPointTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointTime = (global::System.DateTime?) content.GetValueForProperty("RecoveryPointTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("Subnet")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).Subnet = (string) content.GetValueForProperty("Subnet",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).Subnet, 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 FailoverProtectedItemProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProtectedItemName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).ProtectedItemName = (string) content.GetValueForProperty("ProtectedItemName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).ProtectedItemName, global::System.Convert.ToString); + } + if (content.Contains("VMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).VMName = (string) content.GetValueForProperty("VMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).VMName, global::System.Convert.ToString); + } + if (content.Contains("TestVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).TestVMName = (string) content.GetValueForProperty("TestVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).TestVMName, global::System.Convert.ToString); + } + if (content.Contains("RecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointId = (string) content.GetValueForProperty("RecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("RecoveryPointTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointTime = (global::System.DateTime?) content.GetValueForProperty("RecoveryPointTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).RecoveryPointTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("Subnet")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).Subnet = (string) content.GetValueForProperty("Subnet",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal)this).Subnet, 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.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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(); + } + } + /// Failover properties of the protected item. + [System.ComponentModel.TypeConverter(typeof(FailoverProtectedItemPropertiesTypeConverter))] + public partial interface IFailoverProtectedItemProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.TypeConverter.cs new file mode 100644 index 00000000000..f46117f2aec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FailoverProtectedItemPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FailoverProtectedItemProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FailoverProtectedItemProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FailoverProtectedItemProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.cs new file mode 100644 index 00000000000..92e2c23656e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Failover properties of the protected item. + public partial class FailoverProtectedItemProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal + { + + /// Internal Acessors for NetworkName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.NetworkName { get => this._networkName; set { {_networkName = value;} } } + + /// Internal Acessors for ProtectedItemName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.ProtectedItemName { get => this._protectedItemName; set { {_protectedItemName = value;} } } + + /// Internal Acessors for RecoveryPointId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.RecoveryPointId { get => this._recoveryPointId; set { {_recoveryPointId = value;} } } + + /// Internal Acessors for RecoveryPointTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.RecoveryPointTime { get => this._recoveryPointTime; set { {_recoveryPointTime = value;} } } + + /// Internal Acessors for Subnet + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.Subnet { get => this._subnet; set { {_subnet = value;} } } + + /// Internal Acessors for TestVMName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.TestVMName { get => this._testVMName; set { {_testVMName = value;} } } + + /// Internal Acessors for VMName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemPropertiesInternal.VMName { get => this._vMName; set { {_vMName = value;} } } + + /// Backing field for property. + private string _networkName; + + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NetworkName { get => this._networkName; } + + /// Backing field for property. + private string _protectedItemName; + + /// Gets or sets the protected item name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProtectedItemName { get => this._protectedItemName; } + + /// Backing field for property. + private string _recoveryPointId; + + /// Gets or sets the recovery point Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RecoveryPointId { get => this._recoveryPointId; } + + /// Backing field for property. + private global::System.DateTime? _recoveryPointTime; + + /// Gets or sets the recovery point time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? RecoveryPointTime { get => this._recoveryPointTime; } + + /// Backing field for property. + private string _subnet; + + /// Gets or sets the network subnet. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Subnet { get => this._subnet; } + + /// Backing field for property. + private string _testVMName; + + /// Gets or sets the test VM name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestVMName { get => this._testVMName; } + + /// Backing field for property. + private string _vMName; + + /// Gets or sets the VM name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VMName { get => this._vMName; } + + /// Creates an new instance. + public FailoverProtectedItemProperties() + { + + } + } + /// Failover properties of the protected item. + public partial interface IFailoverProtectedItemProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the network name.", + SerializedName = @"networkName", + PossibleTypes = new [] { typeof(string) })] + string NetworkName { get; } + /// Gets or sets the protected item name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + string ProtectedItemName { get; } + /// Gets or sets the recovery point Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the recovery point Id.", + SerializedName = @"recoveryPointId", + PossibleTypes = new [] { typeof(string) })] + string RecoveryPointId { get; } + /// Gets or sets the recovery point time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the recovery point time.", + SerializedName = @"recoveryPointTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? RecoveryPointTime { get; } + /// Gets or sets the network subnet. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the network subnet.", + SerializedName = @"subnet", + PossibleTypes = new [] { typeof(string) })] + string Subnet { get; } + /// Gets or sets the test VM name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test VM name.", + SerializedName = @"testVmName", + PossibleTypes = new [] { typeof(string) })] + string TestVMName { get; } + /// Gets or sets the VM name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the VM name.", + SerializedName = @"vmName", + PossibleTypes = new [] { typeof(string) })] + string VMName { get; } + + } + /// Failover properties of the protected item. + internal partial interface IFailoverProtectedItemPropertiesInternal + + { + /// Gets or sets the network name. + string NetworkName { get; set; } + /// Gets or sets the protected item name. + string ProtectedItemName { get; set; } + /// Gets or sets the recovery point Id. + string RecoveryPointId { get; set; } + /// Gets or sets the recovery point time. + global::System.DateTime? RecoveryPointTime { get; set; } + /// Gets or sets the network subnet. + string Subnet { get; set; } + /// Gets or sets the test VM name. + string TestVMName { get; set; } + /// Gets or sets the VM name. + string VMName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.json.cs new file mode 100644 index 00000000000..f79ae0ae085 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/FailoverProtectedItemProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Failover properties of the protected item. + public partial class FailoverProtectedItemProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal FailoverProtectedItemProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_protectedItemName = If( json?.PropertyT("protectedItemName"), out var __jsonProtectedItemName) ? (string)__jsonProtectedItemName : (string)_protectedItemName;} + {_vMName = If( json?.PropertyT("vmName"), out var __jsonVMName) ? (string)__jsonVMName : (string)_vMName;} + {_testVMName = If( json?.PropertyT("testVmName"), out var __jsonTestVMName) ? (string)__jsonTestVMName : (string)_testVMName;} + {_recoveryPointId = If( json?.PropertyT("recoveryPointId"), out var __jsonRecoveryPointId) ? (string)__jsonRecoveryPointId : (string)_recoveryPointId;} + {_recoveryPointTime = If( json?.PropertyT("recoveryPointTime"), out var __jsonRecoveryPointTime) ? global::System.DateTime.TryParse((string)__jsonRecoveryPointTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonRecoveryPointTimeValue) ? __jsonRecoveryPointTimeValue : _recoveryPointTime : _recoveryPointTime;} + {_networkName = If( json?.PropertyT("networkName"), out var __jsonNetworkName) ? (string)__jsonNetworkName : (string)_networkName;} + {_subnet = If( json?.PropertyT("subnet"), out var __jsonSubnet) ? (string)__jsonSubnet : (string)_subnet;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new FailoverProtectedItemProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._protectedItemName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._protectedItemName.ToString()) : null, "protectedItemName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._vMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._vMName.ToString()) : null, "vmName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testVMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testVMName.ToString()) : null, "testVmName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._recoveryPointId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recoveryPointId.ToString()) : null, "recoveryPointId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._recoveryPointTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recoveryPointTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "recoveryPointTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._networkName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._networkName.ToString()) : null, "networkName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._subnet)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._subnet.ToString()) : null, "subnet" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.PowerShell.cs new file mode 100644 index 00000000000..5961ae0b55f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents of a connection's group information. + [System.ComponentModel.TypeConverter(typeof(GroupConnectivityInformationTypeConverter))] + public partial class GroupConnectivityInformation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GroupConnectivityInformation(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GroupConnectivityInformation(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GroupConnectivityInformation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("MemberName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).MemberName = (string) content.GetValueForProperty("MemberName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).MemberName, global::System.Convert.ToString); + } + if (content.Contains("CustomerVisibleFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).CustomerVisibleFqdn = (System.Collections.Generic.List) content.GetValueForProperty("CustomerVisibleFqdn",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).CustomerVisibleFqdn, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("InternalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).InternalFqdn = (string) content.GetValueForProperty("InternalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).InternalFqdn, global::System.Convert.ToString); + } + if (content.Contains("RedirectMapId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).RedirectMapId = (string) content.GetValueForProperty("RedirectMapId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).RedirectMapId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceArmRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).PrivateLinkServiceArmRegion = (string) content.GetValueForProperty("PrivateLinkServiceArmRegion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).PrivateLinkServiceArmRegion, 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 GroupConnectivityInformation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("MemberName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).MemberName = (string) content.GetValueForProperty("MemberName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).MemberName, global::System.Convert.ToString); + } + if (content.Contains("CustomerVisibleFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).CustomerVisibleFqdn = (System.Collections.Generic.List) content.GetValueForProperty("CustomerVisibleFqdn",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).CustomerVisibleFqdn, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("InternalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).InternalFqdn = (string) content.GetValueForProperty("InternalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).InternalFqdn, global::System.Convert.ToString); + } + if (content.Contains("RedirectMapId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).RedirectMapId = (string) content.GetValueForProperty("RedirectMapId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).RedirectMapId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceArmRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).PrivateLinkServiceArmRegion = (string) content.GetValueForProperty("PrivateLinkServiceArmRegion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal)this).PrivateLinkServiceArmRegion, 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.RecoveryServicesDataReplication.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(); + } + } + /// Represents of a connection's group information. + [System.ComponentModel.TypeConverter(typeof(GroupConnectivityInformationTypeConverter))] + public partial interface IGroupConnectivityInformation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.TypeConverter.cs new file mode 100644 index 00000000000..82775a04c23 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GroupConnectivityInformationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GroupConnectivityInformation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GroupConnectivityInformation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GroupConnectivityInformation.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.cs new file mode 100644 index 00000000000..f4adb0bbc25 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents of a connection's group information. + public partial class GroupConnectivityInformation : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformationInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _customerVisibleFqdn; + + /// Gets or sets customer visible FQDNs. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List CustomerVisibleFqdn { get => this._customerVisibleFqdn; set => this._customerVisibleFqdn = value; } + + /// Backing field for property. + private string _groupId; + + /// Gets or sets group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string GroupId { get => this._groupId; set => this._groupId = value; } + + /// Backing field for property. + private string _internalFqdn; + + /// Gets or sets Internal Fqdn. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InternalFqdn { get => this._internalFqdn; set => this._internalFqdn = value; } + + /// Backing field for property. + private string _memberName; + + /// Gets or sets member name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MemberName { get => this._memberName; set => this._memberName = value; } + + /// Backing field for property. + private string _privateLinkServiceArmRegion; + + /// Gets or sets the private link service arm region. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PrivateLinkServiceArmRegion { get => this._privateLinkServiceArmRegion; set => this._privateLinkServiceArmRegion = value; } + + /// Backing field for property. + private string _redirectMapId; + + /// Gets or sets the redirect map id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RedirectMapId { get => this._redirectMapId; set => this._redirectMapId = value; } + + /// Creates an new instance. + public GroupConnectivityInformation() + { + + } + } + /// Represents of a connection's group information. + public partial interface IGroupConnectivityInformation : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets customer visible FQDNs. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets customer visible FQDNs.", + SerializedName = @"customerVisibleFqdns", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List CustomerVisibleFqdn { get; set; } + /// Gets or sets group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets group id.", + SerializedName = @"groupId", + PossibleTypes = new [] { typeof(string) })] + string GroupId { get; set; } + /// Gets or sets Internal Fqdn. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets Internal Fqdn.", + SerializedName = @"internalFqdn", + PossibleTypes = new [] { typeof(string) })] + string InternalFqdn { get; set; } + /// Gets or sets member name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets member name.", + SerializedName = @"memberName", + PossibleTypes = new [] { typeof(string) })] + string MemberName { get; set; } + /// Gets or sets the private link service arm region. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the private link service arm region.", + SerializedName = @"privateLinkServiceArmRegion", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceArmRegion { get; set; } + /// Gets or sets the redirect map id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the redirect map id.", + SerializedName = @"redirectMapId", + PossibleTypes = new [] { typeof(string) })] + string RedirectMapId { get; set; } + + } + /// Represents of a connection's group information. + internal partial interface IGroupConnectivityInformationInternal + + { + /// Gets or sets customer visible FQDNs. + System.Collections.Generic.List CustomerVisibleFqdn { get; set; } + /// Gets or sets group id. + string GroupId { get; set; } + /// Gets or sets Internal Fqdn. + string InternalFqdn { get; set; } + /// Gets or sets member name. + string MemberName { get; set; } + /// Gets or sets the private link service arm region. + string PrivateLinkServiceArmRegion { get; set; } + /// Gets or sets the redirect map id. + string RedirectMapId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.json.cs new file mode 100644 index 00000000000..867f667d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/GroupConnectivityInformation.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents of a connection's group information. + public partial class GroupConnectivityInformation + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new GroupConnectivityInformation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal GroupConnectivityInformation(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_groupId = If( json?.PropertyT("groupId"), out var __jsonGroupId) ? (string)__jsonGroupId : (string)_groupId;} + {_memberName = If( json?.PropertyT("memberName"), out var __jsonMemberName) ? (string)__jsonMemberName : (string)_memberName;} + {_customerVisibleFqdn = If( json?.PropertyT("customerVisibleFqdns"), out var __jsonCustomerVisibleFqdns) ? If( __jsonCustomerVisibleFqdns as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _customerVisibleFqdn;} + {_internalFqdn = If( json?.PropertyT("internalFqdn"), out var __jsonInternalFqdn) ? (string)__jsonInternalFqdn : (string)_internalFqdn;} + {_redirectMapId = If( json?.PropertyT("redirectMapId"), out var __jsonRedirectMapId) ? (string)__jsonRedirectMapId : (string)_redirectMapId;} + {_privateLinkServiceArmRegion = If( json?.PropertyT("privateLinkServiceArmRegion"), out var __jsonPrivateLinkServiceArmRegion) ? (string)__jsonPrivateLinkServiceArmRegion : (string)_privateLinkServiceArmRegion;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._groupId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._groupId.ToString()) : null, "groupId" ,container.Add ); + AddIf( null != (((object)this._memberName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._memberName.ToString()) : null, "memberName" ,container.Add ); + if (null != this._customerVisibleFqdn) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._customerVisibleFqdn ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("customerVisibleFqdns",__w); + } + AddIf( null != (((object)this._internalFqdn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._internalFqdn.ToString()) : null, "internalFqdn" ,container.Add ); + AddIf( null != (((object)this._redirectMapId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._redirectMapId.ToString()) : null, "redirectMapId" ,container.Add ); + AddIf( null != (((object)this._privateLinkServiceArmRegion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._privateLinkServiceArmRegion.ToString()) : null, "privateLinkServiceArmRegion" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.PowerShell.cs new file mode 100644 index 00000000000..41f276a10af --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.PowerShell.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Health error model. + [System.ComponentModel.TypeConverter(typeof(HealthErrorModelTypeConverter))] + public partial class HealthErrorModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHealthErrorModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HealthErrorModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HealthErrorModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HealthErrorModel(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AffectedResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceType = (string) content.GetValueForProperty("AffectedResourceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedResourceCorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceCorrelationId = (System.Collections.Generic.List) content.GetValueForProperty("AffectedResourceCorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceCorrelationId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ChildError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).ChildError = (System.Collections.Generic.List) content.GetValueForProperty("ChildError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).ChildError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.InnerHealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("HealthCategory")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).HealthCategory = (string) content.GetValueForProperty("HealthCategory",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).HealthCategory, global::System.Convert.ToString); + } + if (content.Contains("Category")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Category = (string) content.GetValueForProperty("Category",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Category, global::System.Convert.ToString); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Source")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Source = (string) content.GetValueForProperty("Source",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Source, global::System.Convert.ToString); + } + if (content.Contains("CreationTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).CreationTime = (global::System.DateTime?) content.GetValueForProperty("CreationTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).CreationTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("IsCustomerResolvable")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).IsCustomerResolvable = (bool?) content.GetValueForProperty("IsCustomerResolvable",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).IsCustomerResolvable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Summary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Summary = (string) content.GetValueForProperty("Summary",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Summary, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Caus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Caus = (string) content.GetValueForProperty("Caus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Caus, global::System.Convert.ToString); + } + if (content.Contains("Recommendation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Recommendation = (string) content.GetValueForProperty("Recommendation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Recommendation, 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 HealthErrorModel(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AffectedResourceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceType = (string) content.GetValueForProperty("AffectedResourceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedResourceCorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceCorrelationId = (System.Collections.Generic.List) content.GetValueForProperty("AffectedResourceCorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).AffectedResourceCorrelationId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ChildError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).ChildError = (System.Collections.Generic.List) content.GetValueForProperty("ChildError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).ChildError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.InnerHealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("HealthCategory")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).HealthCategory = (string) content.GetValueForProperty("HealthCategory",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).HealthCategory, global::System.Convert.ToString); + } + if (content.Contains("Category")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Category = (string) content.GetValueForProperty("Category",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Category, global::System.Convert.ToString); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Source")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Source = (string) content.GetValueForProperty("Source",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Source, global::System.Convert.ToString); + } + if (content.Contains("CreationTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).CreationTime = (global::System.DateTime?) content.GetValueForProperty("CreationTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).CreationTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("IsCustomerResolvable")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).IsCustomerResolvable = (bool?) content.GetValueForProperty("IsCustomerResolvable",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).IsCustomerResolvable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Summary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Summary = (string) content.GetValueForProperty("Summary",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Summary, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Caus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Caus = (string) content.GetValueForProperty("Caus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Caus, global::System.Convert.ToString); + } + if (content.Contains("Recommendation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Recommendation = (string) content.GetValueForProperty("Recommendation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal)this).Recommendation, 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.RecoveryServicesDataReplication.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(); + } + } + /// Health error model. + [System.ComponentModel.TypeConverter(typeof(HealthErrorModelTypeConverter))] + public partial interface IHealthErrorModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.TypeConverter.cs new file mode 100644 index 00000000000..eb8d598a5c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HealthErrorModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHealthErrorModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HealthErrorModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HealthErrorModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HealthErrorModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.cs new file mode 100644 index 00000000000..4822bc985d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.cs @@ -0,0 +1,354 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Health error model. + public partial class HealthErrorModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _affectedResourceCorrelationId; + + /// + /// Gets or sets the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected + /// by a specific category and severity as well as count of item affected by an specific issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List AffectedResourceCorrelationId { get => this._affectedResourceCorrelationId; set => this._affectedResourceCorrelationId = value; } + + /// Backing field for property. + private string _affectedResourceType; + + /// Gets or sets the type of affected resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AffectedResourceType { get => this._affectedResourceType; set => this._affectedResourceType = value; } + + /// Backing field for property. + private string _category; + + /// Gets or sets the error category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Category { get => this._category; } + + /// Backing field for property. + private string _caus; + + /// Gets or sets possible causes of the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Caus { get => this._caus; } + + /// Backing field for property. + private System.Collections.Generic.List _childError; + + /// Gets or sets a list of child health errors associated with this error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ChildError { get => this._childError; set => this._childError = value; } + + /// Backing field for property. + private string _code; + + /// Gets or sets the error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private global::System.DateTime? _creationTime; + + /// Gets or sets the error creation time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? CreationTime { get => this._creationTime; } + + /// Backing field for property. + private string _healthCategory; + + /// Gets or sets the health category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HealthCategory { get => this._healthCategory; } + + /// Backing field for property. + private bool? _isCustomerResolvable; + + /// Gets or sets a value indicating whether the error is customer resolvable. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsCustomerResolvable { get => this._isCustomerResolvable; } + + /// Backing field for property. + private string _message; + + /// Gets or sets the error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Category + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Category { get => this._category; set { {_category = value;} } } + + /// Internal Acessors for Caus + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Caus { get => this._caus; set { {_caus = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for CreationTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.CreationTime { get => this._creationTime; set { {_creationTime = value;} } } + + /// Internal Acessors for HealthCategory + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.HealthCategory { get => this._healthCategory; set { {_healthCategory = value;} } } + + /// Internal Acessors for IsCustomerResolvable + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.IsCustomerResolvable { get => this._isCustomerResolvable; set { {_isCustomerResolvable = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Recommendation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Recommendation { get => this._recommendation; set { {_recommendation = value;} } } + + /// Internal Acessors for Severity + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Severity { get => this._severity; set { {_severity = value;} } } + + /// Internal Acessors for Source + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Source { get => this._source; set { {_source = value;} } } + + /// Internal Acessors for Summary + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModelInternal.Summary { get => this._summary; set { {_summary = value;} } } + + /// Backing field for property. + private string _recommendation; + + /// Gets or sets recommended action to resolve the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Recommendation { get => this._recommendation; } + + /// Backing field for property. + private string _severity; + + /// Gets or sets the error severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Severity { get => this._severity; } + + /// Backing field for property. + private string _source; + + /// Gets or sets the error source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Source { get => this._source; } + + /// Backing field for property. + private string _summary; + + /// Gets or sets the error summary. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Summary { get => this._summary; } + + /// Creates an new instance. + public HealthErrorModel() + { + + } + } + /// Health error model. + public partial interface IHealthErrorModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Gets or sets the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected + /// by a specific category and severity as well as count of item affected by an specific issue. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected by a specific category and severity as well as count of item affected by an specific issue.", + SerializedName = @"affectedResourceCorrelationIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AffectedResourceCorrelationId { get; set; } + /// Gets or sets the type of affected resource type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of affected resource type.", + SerializedName = @"affectedResourceType", + PossibleTypes = new [] { typeof(string) })] + string AffectedResourceType { get; set; } + /// Gets or sets the error category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error category.", + SerializedName = @"category", + PossibleTypes = new [] { typeof(string) })] + string Category { get; } + /// Gets or sets possible causes of the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets possible causes of the error.", + SerializedName = @"causes", + PossibleTypes = new [] { typeof(string) })] + string Caus { get; } + /// Gets or sets a list of child health errors associated with this error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a list of child health errors associated with this error.", + SerializedName = @"childErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel) })] + System.Collections.Generic.List ChildError { get; set; } + /// Gets or sets the error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Gets or sets the error creation time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error creation time.", + SerializedName = @"creationTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreationTime { get; } + /// Gets or sets the health category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the health category.", + SerializedName = @"healthCategory", + PossibleTypes = new [] { typeof(string) })] + string HealthCategory { get; } + /// Gets or sets a value indicating whether the error is customer resolvable. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether the error is customer resolvable.", + SerializedName = @"isCustomerResolvable", + PossibleTypes = new [] { typeof(bool) })] + bool? IsCustomerResolvable { get; } + /// Gets or sets the error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// Gets or sets recommended action to resolve the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets recommended action to resolve the error.", + SerializedName = @"recommendation", + PossibleTypes = new [] { typeof(string) })] + string Recommendation { get; } + /// Gets or sets the error severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error severity.", + SerializedName = @"severity", + PossibleTypes = new [] { typeof(string) })] + string Severity { get; } + /// Gets or sets the error source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error source.", + SerializedName = @"source", + PossibleTypes = new [] { typeof(string) })] + string Source { get; } + /// Gets or sets the error summary. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error summary.", + SerializedName = @"summary", + PossibleTypes = new [] { typeof(string) })] + string Summary { get; } + + } + /// Health error model. + internal partial interface IHealthErrorModelInternal + + { + /// + /// Gets or sets the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected + /// by a specific category and severity as well as count of item affected by an specific issue. + /// + System.Collections.Generic.List AffectedResourceCorrelationId { get; set; } + /// Gets or sets the type of affected resource type. + string AffectedResourceType { get; set; } + /// Gets or sets the error category. + string Category { get; set; } + /// Gets or sets possible causes of the error. + string Caus { get; set; } + /// Gets or sets a list of child health errors associated with this error. + System.Collections.Generic.List ChildError { get; set; } + /// Gets or sets the error code. + string Code { get; set; } + /// Gets or sets the error creation time. + global::System.DateTime? CreationTime { get; set; } + /// Gets or sets the health category. + string HealthCategory { get; set; } + /// Gets or sets a value indicating whether the error is customer resolvable. + bool? IsCustomerResolvable { get; set; } + /// Gets or sets the error message. + string Message { get; set; } + /// Gets or sets recommended action to resolve the error. + string Recommendation { get; set; } + /// Gets or sets the error severity. + string Severity { get; set; } + /// Gets or sets the error source. + string Source { get; set; } + /// Gets or sets the error summary. + string Summary { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.json.cs new file mode 100644 index 00000000000..04fbc2d79b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HealthErrorModel.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Health error model. + public partial class HealthErrorModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HealthErrorModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HealthErrorModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_affectedResourceType = If( json?.PropertyT("affectedResourceType"), out var __jsonAffectedResourceType) ? (string)__jsonAffectedResourceType : (string)_affectedResourceType;} + {_affectedResourceCorrelationId = If( json?.PropertyT("affectedResourceCorrelationIds"), out var __jsonAffectedResourceCorrelationIds) ? If( __jsonAffectedResourceCorrelationIds as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _affectedResourceCorrelationId;} + {_childError = If( json?.PropertyT("childErrors"), out var __jsonChildErrors) ? If( __jsonChildErrors as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.InnerHealthErrorModel.FromJson(__p) )) ))() : null : _childError;} + {_code = If( json?.PropertyT("code"), out var __jsonCode) ? (string)__jsonCode : (string)_code;} + {_healthCategory = If( json?.PropertyT("healthCategory"), out var __jsonHealthCategory) ? (string)__jsonHealthCategory : (string)_healthCategory;} + {_category = If( json?.PropertyT("category"), out var __jsonCategory) ? (string)__jsonCategory : (string)_category;} + {_severity = If( json?.PropertyT("severity"), out var __jsonSeverity) ? (string)__jsonSeverity : (string)_severity;} + {_source = If( json?.PropertyT("source"), out var __jsonSource) ? (string)__jsonSource : (string)_source;} + {_creationTime = If( json?.PropertyT("creationTime"), out var __jsonCreationTime) ? global::System.DateTime.TryParse((string)__jsonCreationTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreationTimeValue) ? __jsonCreationTimeValue : _creationTime : _creationTime;} + {_isCustomerResolvable = If( json?.PropertyT("isCustomerResolvable"), out var __jsonIsCustomerResolvable) ? (bool?)__jsonIsCustomerResolvable : _isCustomerResolvable;} + {_summary = If( json?.PropertyT("summary"), out var __jsonSummary) ? (string)__jsonSummary : (string)_summary;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)_message;} + {_caus = If( json?.PropertyT("causes"), out var __jsonCauses) ? (string)__jsonCauses : (string)_caus;} + {_recommendation = If( json?.PropertyT("recommendation"), out var __jsonRecommendation) ? (string)__jsonRecommendation : (string)_recommendation;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._affectedResourceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._affectedResourceType.ToString()) : null, "affectedResourceType" ,container.Add ); + if (null != this._affectedResourceCorrelationId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._affectedResourceCorrelationId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("affectedResourceCorrelationIds",__w); + } + if (null != this._childError) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._childError ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("childErrors",__r); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._healthCategory)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._healthCategory.ToString()) : null, "healthCategory" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._category)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._category.ToString()) : null, "category" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._severity)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._severity.ToString()) : null, "severity" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._source)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._source.ToString()) : null, "source" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._creationTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._creationTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "creationTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isCustomerResolvable ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isCustomerResolvable) : null, "isCustomerResolvable" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._summary)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._summary.ToString()) : null, "summary" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._caus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._caus.ToString()) : null, "causes" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._recommendation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recommendation.ToString()) : null, "recommendation" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..f348f5d40fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.PowerShell.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV migrate fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVMigrateFabricModelCustomPropertiesTypeConverter))] + public partial class HyperVMigrateFabricModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVMigrateFabricModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVMigrateFabricModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVMigrateFabricModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("HyperVSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).HyperVSiteId = (string) content.GetValueForProperty("HyperVSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).HyperVSiteId, global::System.Convert.ToString); + } + if (content.Contains("FabricResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricResourceId = (string) content.GetValueForProperty("FabricResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricResourceId, global::System.Convert.ToString); + } + if (content.Contains("FabricContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricContainerId = (string) content.GetValueForProperty("FabricContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricContainerId, global::System.Convert.ToString); + } + if (content.Contains("MigrationSolutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId = (string) content.GetValueForProperty("MigrationSolutionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId, global::System.Convert.ToString); + } + if (content.Contains("MigrationHubUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationHubUri = (string) content.GetValueForProperty("MigrationHubUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationHubUri, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, 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 HyperVMigrateFabricModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("HyperVSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).HyperVSiteId = (string) content.GetValueForProperty("HyperVSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).HyperVSiteId, global::System.Convert.ToString); + } + if (content.Contains("FabricResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricResourceId = (string) content.GetValueForProperty("FabricResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricResourceId, global::System.Convert.ToString); + } + if (content.Contains("FabricContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricContainerId = (string) content.GetValueForProperty("FabricContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).FabricContainerId, global::System.Convert.ToString); + } + if (content.Contains("MigrationSolutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId = (string) content.GetValueForProperty("MigrationSolutionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId, global::System.Convert.ToString); + } + if (content.Contains("MigrationHubUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationHubUri = (string) content.GetValueForProperty("MigrationHubUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal)this).MigrationHubUri, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV migrate fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVMigrateFabricModelCustomPropertiesTypeConverter))] + public partial interface IHyperVMigrateFabricModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..0e99befdc9a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVMigrateFabricModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVMigrateFabricModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVMigrateFabricModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVMigrateFabricModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.cs new file mode 100644 index 00000000000..db5f2755109 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV migrate fabric model custom properties. + public partial class HyperVMigrateFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties __fabricModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties(); + + /// Backing field for property. + private string _fabricContainerId; + + /// Gets or sets the fabric container Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricContainerId { get => this._fabricContainerId; } + + /// Backing field for property. + private string _fabricResourceId; + + /// Gets or sets the fabric resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricResourceId { get => this._fabricResourceId; } + + /// Backing field for property. + private string _hyperVSiteId; + + /// Gets or sets the ARM Id of the HyperV site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HyperVSiteId { get => this._hyperVSiteId; set => this._hyperVSiteId = value; } + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVMigrate"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)__fabricModelCustomProperties).InstanceType = "HyperVMigrate"; } + + /// Internal Acessors for FabricContainerId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal.FabricContainerId { get => this._fabricContainerId; set { {_fabricContainerId = value;} } } + + /// Internal Acessors for FabricResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal.FabricResourceId { get => this._fabricResourceId; set { {_fabricResourceId = value;} } } + + /// Internal Acessors for MigrationHubUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomPropertiesInternal.MigrationHubUri { get => this._migrationHubUri; set { {_migrationHubUri = value;} } } + + /// Backing field for property. + private string _migrationHubUri; + + /// Gets or sets the migration hub Uri. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrationHubUri { get => this._migrationHubUri; } + + /// Backing field for property. + private string _migrationSolutionId; + + /// Gets or sets the migration solution ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrationSolutionId { get => this._migrationSolutionId; set => this._migrationSolutionId = value; } + + /// + /// Creates an new instance. + /// + public HyperVMigrateFabricModelCustomProperties() + { + this.__fabricModelCustomProperties.InstanceType = "HyperVMigrate"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__fabricModelCustomProperties), __fabricModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__fabricModelCustomProperties), __fabricModelCustomProperties); + } + } + /// HyperV migrate fabric model custom properties. + public partial interface IHyperVMigrateFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties + { + /// Gets or sets the fabric container Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric container Id.", + SerializedName = @"fabricContainerId", + PossibleTypes = new [] { typeof(string) })] + string FabricContainerId { get; } + /// Gets or sets the fabric resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric resource Id.", + SerializedName = @"fabricResourceId", + PossibleTypes = new [] { typeof(string) })] + string FabricResourceId { get; } + /// Gets or sets the ARM Id of the HyperV site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the HyperV site.", + SerializedName = @"hyperVSiteId", + PossibleTypes = new [] { typeof(string) })] + string HyperVSiteId { get; set; } + /// Gets or sets the migration hub Uri. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the migration hub Uri.", + SerializedName = @"migrationHubUri", + PossibleTypes = new [] { typeof(string) })] + string MigrationHubUri { get; } + /// Gets or sets the migration solution ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the migration solution ARM Id.", + SerializedName = @"migrationSolutionId", + PossibleTypes = new [] { typeof(string) })] + string MigrationSolutionId { get; set; } + + } + /// HyperV migrate fabric model custom properties. + internal partial interface IHyperVMigrateFabricModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal + { + /// Gets or sets the fabric container Id. + string FabricContainerId { get; set; } + /// Gets or sets the fabric resource Id. + string FabricResourceId { get; set; } + /// Gets or sets the ARM Id of the HyperV site. + string HyperVSiteId { get; set; } + /// Gets or sets the migration hub Uri. + string MigrationHubUri { get; set; } + /// Gets or sets the migration solution ARM Id. + string MigrationSolutionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.json.cs new file mode 100644 index 00000000000..36dd18ef795 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVMigrateFabricModelCustomProperties.json.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV migrate fabric model custom properties. + public partial class HyperVMigrateFabricModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVMigrateFabricModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVMigrateFabricModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVMigrateFabricModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __fabricModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties(json); + {_hyperVSiteId = If( json?.PropertyT("hyperVSiteId"), out var __jsonHyperVSiteId) ? (string)__jsonHyperVSiteId : (string)_hyperVSiteId;} + {_fabricResourceId = If( json?.PropertyT("fabricResourceId"), out var __jsonFabricResourceId) ? (string)__jsonFabricResourceId : (string)_fabricResourceId;} + {_fabricContainerId = If( json?.PropertyT("fabricContainerId"), out var __jsonFabricContainerId) ? (string)__jsonFabricContainerId : (string)_fabricContainerId;} + {_migrationSolutionId = If( json?.PropertyT("migrationSolutionId"), out var __jsonMigrationSolutionId) ? (string)__jsonMigrationSolutionId : (string)_migrationSolutionId;} + {_migrationHubUri = If( json?.PropertyT("migrationHubUri"), out var __jsonMigrationHubUri) ? (string)__jsonMigrationHubUri : (string)_migrationHubUri;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __fabricModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != (((object)this._hyperVSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._hyperVSiteId.ToString()) : null, "hyperVSiteId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricResourceId.ToString()) : null, "fabricResourceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricContainerId.ToString()) : null, "fabricContainerId" ,container.Add ); + } + AddIf( null != (((object)this._migrationSolutionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrationSolutionId.ToString()) : null, "migrationSolutionId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._migrationHubUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrationHubUri.ToString()) : null, "migrationHubUri" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.PowerShell.cs new file mode 100644 index 00000000000..8ceefccb627 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.PowerShell.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperVToAzStack disk input. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcidiskInputTypeConverter))] + public partial class HyperVToAzStackHcidiskInput + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHcidiskInput(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHcidiskInput(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHcidiskInput(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskController")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskController = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs) content.GetValueForProperty("DiskController",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskController, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputsTypeConverter.ConvertFrom); + } + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskId = (string) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskSizeGb")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskSizeGb = (long) content.GetValueForProperty("DiskSizeGb",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskSizeGb, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskFileFormat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskFileFormat = (string) content.GetValueForProperty("DiskFileFormat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskFileFormat, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsOSDisk = (bool) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskIdentifier")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskIdentifier = (string) content.GetValueForProperty("DiskIdentifier",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskIdentifier, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerName = (string) content.GetValueForProperty("DiskControllerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerName, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerId = (int?) content.GetValueForProperty("DiskControllerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("DiskControllerLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerLocation = (int?) content.GetValueForProperty("DiskControllerLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerLocation, (__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 HyperVToAzStackHcidiskInput(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskController")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskController = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs) content.GetValueForProperty("DiskController",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskController, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputsTypeConverter.ConvertFrom); + } + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskId = (string) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskSizeGb")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskSizeGb = (long) content.GetValueForProperty("DiskSizeGb",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskSizeGb, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskFileFormat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskFileFormat = (string) content.GetValueForProperty("DiskFileFormat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskFileFormat, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsOSDisk = (bool) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskIdentifier")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskIdentifier = (string) content.GetValueForProperty("DiskIdentifier",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskIdentifier, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerName = (string) content.GetValueForProperty("DiskControllerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerName, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerId = (int?) content.GetValueForProperty("DiskControllerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("DiskControllerLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerLocation = (int?) content.GetValueForProperty("DiskControllerLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal)this).DiskControllerLocation, (__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.RecoveryServicesDataReplication.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(); + } + } + /// HyperVToAzStack disk input. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcidiskInputTypeConverter))] + public partial interface IHyperVToAzStackHcidiskInput + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.TypeConverter.cs new file mode 100644 index 00000000000..97511a25510 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHcidiskInputTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHcidiskInput.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHcidiskInput.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHcidiskInput.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.cs new file mode 100644 index 00000000000..8c65f29a4cf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.cs @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStack disk input. + public partial class HyperVToAzStackHcidiskInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal + { + + /// Backing field for property. + private long? _diskBlockSize; + + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskBlockSize { get => this._diskBlockSize; set => this._diskBlockSize = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs _diskController; + + /// Disk controller. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs DiskController { get => (this._diskController = this._diskController ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputs()); set => this._diskController = value; } + + /// Gets or sets the controller ID. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DiskControllerId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerId = value ?? default(int); } + + /// Gets or sets the controller Location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DiskControllerLocation { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerLocation; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerLocation = value ?? default(int); } + + /// Gets or sets the controller name (IDE,SCSI). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DiskControllerName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerName = value ?? null; } + + /// Backing field for property. + private string _diskFileFormat; + + /// Gets or sets the type of the virtual hard disk, vhd or vhdx. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskFileFormat { get => this._diskFileFormat; set => this._diskFileFormat = value; } + + /// Backing field for property. + private string _diskId; + + /// Gets or sets the disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskId { get => this._diskId; set => this._diskId = value; } + + /// Backing field for property. + private string _diskIdentifier; + + /// Gets or sets a value of disk identifier. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskIdentifier { get => this._diskIdentifier; set => this._diskIdentifier = value; } + + /// Backing field for property. + private long? _diskLogicalSectorSize; + + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskLogicalSectorSize { get => this._diskLogicalSectorSize; set => this._diskLogicalSectorSize = value; } + + /// Backing field for property. + private long? _diskPhysicalSectorSize; + + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskPhysicalSectorSize { get => this._diskPhysicalSectorSize; set => this._diskPhysicalSectorSize = value; } + + /// Backing field for property. + private long _diskSizeGb; + + /// Gets or sets the disk size in GB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long DiskSizeGb { get => this._diskSizeGb; set => this._diskSizeGb = value; } + + /// Backing field for property. + private bool? _isDynamic; + + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamic { get => this._isDynamic; set => this._isDynamic = value; } + + /// Backing field for property. + private bool _isOSDisk; + + /// Gets or sets a value indicating whether disk is os disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool IsOSDisk { get => this._isOSDisk; set => this._isOSDisk = value; } + + /// Internal Acessors for DiskController + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInputInternal.DiskController { get => (this._diskController = this._diskController ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputs()); set { {_diskController = value;} } } + + /// Backing field for property. + private string _storageContainerId; + + /// Gets or sets the target storage account ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerId { get => this._storageContainerId; set => this._storageContainerId = value; } + + /// Creates an new instance. + public HyperVToAzStackHcidiskInput() + { + + } + } + /// HyperVToAzStack disk input. + public partial interface IHyperVToAzStackHcidiskInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk block size.", + SerializedName = @"diskBlockSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskBlockSize { get; set; } + /// Gets or sets the controller ID. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller ID.", + SerializedName = @"controllerId", + PossibleTypes = new [] { typeof(int) })] + int? DiskControllerId { get; set; } + /// Gets or sets the controller Location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller Location.", + SerializedName = @"controllerLocation", + PossibleTypes = new [] { typeof(int) })] + int? DiskControllerLocation { get; set; } + /// Gets or sets the controller name (IDE,SCSI). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller name (IDE,SCSI).", + SerializedName = @"controllerName", + PossibleTypes = new [] { typeof(string) })] + string DiskControllerName { get; set; } + /// Gets or sets the type of the virtual hard disk, vhd or vhdx. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of the virtual hard disk, vhd or vhdx.", + SerializedName = @"diskFileFormat", + PossibleTypes = new [] { typeof(string) })] + string DiskFileFormat { get; set; } + /// Gets or sets the disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the disk Id.", + SerializedName = @"diskId", + PossibleTypes = new [] { typeof(string) })] + string DiskId { get; set; } + /// Gets or sets a value of disk identifier. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk identifier.", + SerializedName = @"diskIdentifier", + PossibleTypes = new [] { typeof(string) })] + string DiskIdentifier { get; set; } + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk logical sector size.", + SerializedName = @"diskLogicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskLogicalSectorSize { get; set; } + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk physical sector size.", + SerializedName = @"diskPhysicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskPhysicalSectorSize { get; set; } + /// Gets or sets the disk size in GB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the disk size in GB.", + SerializedName = @"diskSizeGB", + PossibleTypes = new [] { typeof(long) })] + long DiskSizeGb { get; set; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk.", + SerializedName = @"isDynamic", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamic { get; set; } + /// Gets or sets a value indicating whether disk is os disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether disk is os disk.", + SerializedName = @"isOsDisk", + PossibleTypes = new [] { typeof(bool) })] + bool IsOSDisk { get; set; } + /// Gets or sets the target storage account ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target storage account ARM Id.", + SerializedName = @"storageContainerId", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerId { get; set; } + + } + /// HyperVToAzStack disk input. + internal partial interface IHyperVToAzStackHcidiskInputInternal + + { + /// Gets or sets a value of disk block size. + long? DiskBlockSize { get; set; } + /// Disk controller. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs DiskController { get; set; } + /// Gets or sets the controller ID. + int? DiskControllerId { get; set; } + /// Gets or sets the controller Location. + int? DiskControllerLocation { get; set; } + /// Gets or sets the controller name (IDE,SCSI). + string DiskControllerName { get; set; } + /// Gets or sets the type of the virtual hard disk, vhd or vhdx. + string DiskFileFormat { get; set; } + /// Gets or sets the disk Id. + string DiskId { get; set; } + /// Gets or sets a value of disk identifier. + string DiskIdentifier { get; set; } + /// Gets or sets a value of disk logical sector size. + long? DiskLogicalSectorSize { get; set; } + /// Gets or sets a value of disk physical sector size. + long? DiskPhysicalSectorSize { get; set; } + /// Gets or sets the disk size in GB. + long DiskSizeGb { get; set; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + bool? IsDynamic { get; set; } + /// Gets or sets a value indicating whether disk is os disk. + bool IsOSDisk { get; set; } + /// Gets or sets the target storage account ARM Id. + string StorageContainerId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.json.cs new file mode 100644 index 00000000000..fe2041ad0c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcidiskInput.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStack disk input. + public partial class HyperVToAzStackHcidiskInput + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHcidiskInput(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHcidiskInput(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_diskController = If( json?.PropertyT("diskController"), out var __jsonDiskController) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputs.FromJson(__jsonDiskController) : _diskController;} + {_diskId = If( json?.PropertyT("diskId"), out var __jsonDiskId) ? (string)__jsonDiskId : (string)_diskId;} + {_storageContainerId = If( json?.PropertyT("storageContainerId"), out var __jsonStorageContainerId) ? (string)__jsonStorageContainerId : (string)_storageContainerId;} + {_isDynamic = If( json?.PropertyT("isDynamic"), out var __jsonIsDynamic) ? (bool?)__jsonIsDynamic : _isDynamic;} + {_diskSizeGb = If( json?.PropertyT("diskSizeGB"), out var __jsonDiskSizeGb) ? (long)__jsonDiskSizeGb : _diskSizeGb;} + {_diskFileFormat = If( json?.PropertyT("diskFileFormat"), out var __jsonDiskFileFormat) ? (string)__jsonDiskFileFormat : (string)_diskFileFormat;} + {_isOSDisk = If( json?.PropertyT("isOsDisk"), out var __jsonIsOSDisk) ? (bool)__jsonIsOSDisk : _isOSDisk;} + {_diskBlockSize = If( json?.PropertyT("diskBlockSize"), out var __jsonDiskBlockSize) ? (long?)__jsonDiskBlockSize : _diskBlockSize;} + {_diskLogicalSectorSize = If( json?.PropertyT("diskLogicalSectorSize"), out var __jsonDiskLogicalSectorSize) ? (long?)__jsonDiskLogicalSectorSize : _diskLogicalSectorSize;} + {_diskPhysicalSectorSize = If( json?.PropertyT("diskPhysicalSectorSize"), out var __jsonDiskPhysicalSectorSize) ? (long?)__jsonDiskPhysicalSectorSize : _diskPhysicalSectorSize;} + {_diskIdentifier = If( json?.PropertyT("diskIdentifier"), out var __jsonDiskIdentifier) ? (string)__jsonDiskIdentifier : (string)_diskIdentifier;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._diskController ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._diskController.ToJson(null,serializationMode) : null, "diskController" ,container.Add ); + AddIf( null != (((object)this._diskId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskId.ToString()) : null, "diskId" ,container.Add ); + AddIf( null != (((object)this._storageContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerId.ToString()) : null, "storageContainerId" ,container.Add ); + AddIf( null != this._isDynamic ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamic) : null, "isDynamic" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._diskSizeGb), "diskSizeGB" ,container.Add ); + AddIf( null != (((object)this._diskFileFormat)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskFileFormat.ToString()) : null, "diskFileFormat" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean(this._isOSDisk), "isOsDisk" ,container.Add ); + AddIf( null != this._diskBlockSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskBlockSize) : null, "diskBlockSize" ,container.Add ); + AddIf( null != this._diskLogicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskLogicalSectorSize) : null, "diskLogicalSectorSize" ,container.Add ); + AddIf( null != this._diskPhysicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskPhysicalSectorSize) : null, "diskPhysicalSectorSize" ,container.Add ); + AddIf( null != (((object)this._diskIdentifier)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskIdentifier.ToString()) : null, "diskIdentifier" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..f349c7dcccf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.PowerShell.cs @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + /// + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcieventModelCustomPropertiesTypeConverter))] + public partial class HyperVToAzStackHcieventModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHcieventModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHcieventModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHcieventModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("EventSourceFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName = (string) content.GetValueForProperty("EventSourceFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("ProtectedItemFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName = (string) content.GetValueForProperty("ProtectedItemFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("ServerType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ServerType = (string) content.GetValueForProperty("ServerType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ServerType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType, 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 HyperVToAzStackHcieventModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("EventSourceFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName = (string) content.GetValueForProperty("EventSourceFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("ProtectedItemFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName = (string) content.GetValueForProperty("ProtectedItemFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("ServerType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ServerType = (string) content.GetValueForProperty("ServerType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal)this).ServerType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcieventModelCustomPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHcieventModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..3612a2cea81 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHcieventModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHcieventModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHcieventModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHcieventModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.cs new file mode 100644 index 00000000000..878bb635161 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + /// + public partial class HyperVToAzStackHcieventModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties __eventModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties(); + + /// Backing field for property. + private string _eventSourceFriendlyName; + + /// + /// Gets or sets the friendly name of the source which has raised this health event. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EventSourceFriendlyName { get => this._eventSourceFriendlyName; } + + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)__eventModelCustomProperties).InstanceType = "HyperVToAzStackHCI"; } + + /// Internal Acessors for EventSourceFriendlyName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal.EventSourceFriendlyName { get => this._eventSourceFriendlyName; set { {_eventSourceFriendlyName = value;} } } + + /// Internal Acessors for ProtectedItemFriendlyName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal.ProtectedItemFriendlyName { get => this._protectedItemFriendlyName; set { {_protectedItemFriendlyName = value;} } } + + /// Internal Acessors for ServerType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal.ServerType { get => this._serverType; set { {_serverType = value;} } } + + /// Internal Acessors for SourceApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal.SourceApplianceName { get => this._sourceApplianceName; set { {_sourceApplianceName = value;} } } + + /// Internal Acessors for TargetApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomPropertiesInternal.TargetApplianceName { get => this._targetApplianceName; set { {_targetApplianceName = value;} } } + + /// Backing field for property. + private string _protectedItemFriendlyName; + + /// Gets or sets the protected item friendly name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProtectedItemFriendlyName { get => this._protectedItemFriendlyName; } + + /// Backing field for property. + private string _serverType; + + /// Gets or sets the server type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ServerType { get => this._serverType; } + + /// Backing field for property. + private string _sourceApplianceName; + + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceApplianceName { get => this._sourceApplianceName; } + + /// Backing field for property. + private string _targetApplianceName; + + /// Gets or sets the source target name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetApplianceName { get => this._targetApplianceName; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHcieventModelCustomProperties() + { + this.__eventModelCustomProperties.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__eventModelCustomProperties), __eventModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__eventModelCustomProperties), __eventModelCustomProperties); + } + } + /// HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + public partial interface IHyperVToAzStackHcieventModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties + { + /// + /// Gets or sets the friendly name of the source which has raised this health event. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the friendly name of the source which has raised this health event.", + SerializedName = @"eventSourceFriendlyName", + PossibleTypes = new [] { typeof(string) })] + string EventSourceFriendlyName { get; } + /// Gets or sets the protected item friendly name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protected item friendly name.", + SerializedName = @"protectedItemFriendlyName", + PossibleTypes = new [] { typeof(string) })] + string ProtectedItemFriendlyName { get; } + /// Gets or sets the server type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the server type.", + SerializedName = @"serverType", + PossibleTypes = new [] { typeof(string) })] + string ServerType { get; } + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source appliance name.", + SerializedName = @"sourceApplianceName", + PossibleTypes = new [] { typeof(string) })] + string SourceApplianceName { get; } + /// Gets or sets the source target name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source target name.", + SerializedName = @"targetApplianceName", + PossibleTypes = new [] { typeof(string) })] + string TargetApplianceName { get; } + + } + /// HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + internal partial interface IHyperVToAzStackHcieventModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal + { + /// + /// Gets or sets the friendly name of the source which has raised this health event. + /// + string EventSourceFriendlyName { get; set; } + /// Gets or sets the protected item friendly name. + string ProtectedItemFriendlyName { get; set; } + /// Gets or sets the server type. + string ServerType { get; set; } + /// Gets or sets the source appliance name. + string SourceApplianceName { get; set; } + /// Gets or sets the source target name. + string TargetApplianceName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.json.cs new file mode 100644 index 00000000000..a09ae0e9c74 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcieventModelCustomProperties.json.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// HyperV to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + /// + public partial class HyperVToAzStackHcieventModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcieventModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHcieventModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHcieventModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __eventModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties(json); + {_eventSourceFriendlyName = If( json?.PropertyT("eventSourceFriendlyName"), out var __jsonEventSourceFriendlyName) ? (string)__jsonEventSourceFriendlyName : (string)_eventSourceFriendlyName;} + {_protectedItemFriendlyName = If( json?.PropertyT("protectedItemFriendlyName"), out var __jsonProtectedItemFriendlyName) ? (string)__jsonProtectedItemFriendlyName : (string)_protectedItemFriendlyName;} + {_sourceApplianceName = If( json?.PropertyT("sourceApplianceName"), out var __jsonSourceApplianceName) ? (string)__jsonSourceApplianceName : (string)_sourceApplianceName;} + {_targetApplianceName = If( json?.PropertyT("targetApplianceName"), out var __jsonTargetApplianceName) ? (string)__jsonTargetApplianceName : (string)_targetApplianceName;} + {_serverType = If( json?.PropertyT("serverType"), out var __jsonServerType) ? (string)__jsonServerType : (string)_serverType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __eventModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eventSourceFriendlyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._eventSourceFriendlyName.ToString()) : null, "eventSourceFriendlyName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._protectedItemFriendlyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._protectedItemFriendlyName.ToString()) : null, "protectedItemFriendlyName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceApplianceName.ToString()) : null, "sourceApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetApplianceName.ToString()) : null, "targetApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._serverType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._serverType.ToString()) : null, "serverType" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.PowerShell.cs new file mode 100644 index 00000000000..6f7e83b7b8f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.PowerShell.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperVToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcinicInputTypeConverter))] + public partial class HyperVToAzStackHcinicInput + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHcinicInput(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHcinicInput(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHcinicInput(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).SelectionTypeForFailover, global::System.Convert.ToString); + } + if (content.Contains("IsStaticIPMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled = (bool?) content.GetValueForProperty("IsStaticIPMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("IsMacMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsMacMigrationEnabled = (bool?) content.GetValueForProperty("IsMacMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsMacMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal HyperVToAzStackHcinicInput(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).SelectionTypeForFailover, global::System.Convert.ToString); + } + if (content.Contains("IsStaticIPMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled = (bool?) content.GetValueForProperty("IsStaticIPMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("IsMacMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsMacMigrationEnabled = (bool?) content.GetValueForProperty("IsMacMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal)this).IsMacMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperVToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcinicInputTypeConverter))] + public partial interface IHyperVToAzStackHcinicInput + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.TypeConverter.cs new file mode 100644 index 00000000000..e22003a2983 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHcinicInputTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHcinicInput.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHcinicInput.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHcinicInput.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.cs new file mode 100644 index 00000000000..8eaa58029d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStackHCI NIC properties. + public partial class HyperVToAzStackHcinicInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal + { + + /// Backing field for property. + private bool? _isMacMigrationEnabled; + + /// Gets or sets a value indicating whether mac address migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsMacMigrationEnabled { get => this._isMacMigrationEnabled; set => this._isMacMigrationEnabled = value; } + + /// Backing field for property. + private bool? _isStaticIPMigrationEnabled; + + /// Gets or sets a value indicating whether static ip migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsStaticIPMigrationEnabled { get => this._isStaticIPMigrationEnabled; set => this._isStaticIPMigrationEnabled = value; } + + /// Internal Acessors for NetworkName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInputInternal.NetworkName { get => this._networkName; set { {_networkName = value;} } } + + /// Backing field for property. + private string _networkName; + + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NetworkName { get => this._networkName; } + + /// Backing field for property. + private string _nicId; + + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NicId { get => this._nicId; set => this._nicId = value; } + + /// Backing field for property. + private string _selectionTypeForFailover; + + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SelectionTypeForFailover { get => this._selectionTypeForFailover; set => this._selectionTypeForFailover = value; } + + /// Backing field for property. + private string _targetNetworkId; + + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetNetworkId { get => this._targetNetworkId; set => this._targetNetworkId = value; } + + /// Backing field for property. + private string _testNetworkId; + + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestNetworkId { get => this._testNetworkId; set => this._testNetworkId = value; } + + /// Creates an new instance. + public HyperVToAzStackHcinicInput() + { + + } + } + /// HyperVToAzStackHCI NIC properties. + public partial interface IHyperVToAzStackHcinicInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets a value indicating whether mac address migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether mac address migration is enabled.", + SerializedName = @"isMacMigrationEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? IsMacMigrationEnabled { get; set; } + /// Gets or sets a value indicating whether static ip migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether static ip migration is enabled.", + SerializedName = @"isStaticIpMigrationEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? IsStaticIPMigrationEnabled { get; set; } + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the network name.", + SerializedName = @"networkName", + PossibleTypes = new [] { typeof(string) })] + string NetworkName { get; } + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the NIC Id.", + SerializedName = @"nicId", + PossibleTypes = new [] { typeof(string) })] + string NicId { get; set; } + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the selection type of the NIC.", + SerializedName = @"selectionTypeForFailover", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target network Id within AzStackHCI Cluster.", + SerializedName = @"targetNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TargetNetworkId { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target test network Id within AzStackHCI Cluster.", + SerializedName = @"testNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TestNetworkId { get; set; } + + } + /// HyperVToAzStackHCI NIC properties. + internal partial interface IHyperVToAzStackHcinicInputInternal + + { + /// Gets or sets a value indicating whether mac address migration is enabled. + bool? IsMacMigrationEnabled { get; set; } + /// Gets or sets a value indicating whether static ip migration is enabled. + bool? IsStaticIPMigrationEnabled { get; set; } + /// Gets or sets the network name. + string NetworkName { get; set; } + /// Gets or sets the NIC Id. + string NicId { get; set; } + /// Gets or sets the selection type of the NIC. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + string TargetNetworkId { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + string TestNetworkId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.json.cs new file mode 100644 index 00000000000..a287d453f32 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcinicInput.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStackHCI NIC properties. + public partial class HyperVToAzStackHcinicInput + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHcinicInput(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHcinicInput(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nicId = If( json?.PropertyT("nicId"), out var __jsonNicId) ? (string)__jsonNicId : (string)_nicId;} + {_networkName = If( json?.PropertyT("networkName"), out var __jsonNetworkName) ? (string)__jsonNetworkName : (string)_networkName;} + {_targetNetworkId = If( json?.PropertyT("targetNetworkId"), out var __jsonTargetNetworkId) ? (string)__jsonTargetNetworkId : (string)_targetNetworkId;} + {_testNetworkId = If( json?.PropertyT("testNetworkId"), out var __jsonTestNetworkId) ? (string)__jsonTestNetworkId : (string)_testNetworkId;} + {_selectionTypeForFailover = If( json?.PropertyT("selectionTypeForFailover"), out var __jsonSelectionTypeForFailover) ? (string)__jsonSelectionTypeForFailover : (string)_selectionTypeForFailover;} + {_isStaticIPMigrationEnabled = If( json?.PropertyT("isStaticIpMigrationEnabled"), out var __jsonIsStaticIPMigrationEnabled) ? (bool?)__jsonIsStaticIPMigrationEnabled : _isStaticIPMigrationEnabled;} + {_isMacMigrationEnabled = If( json?.PropertyT("isMacMigrationEnabled"), out var __jsonIsMacMigrationEnabled) ? (bool?)__jsonIsMacMigrationEnabled : _isMacMigrationEnabled;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nicId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._nicId.ToString()) : null, "nicId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._networkName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._networkName.ToString()) : null, "networkName" ,container.Add ); + } + AddIf( null != (((object)this._targetNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetNetworkId.ToString()) : null, "targetNetworkId" ,container.Add ); + AddIf( null != (((object)this._testNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testNetworkId.ToString()) : null, "testNetworkId" ,container.Add ); + AddIf( null != (((object)this._selectionTypeForFailover)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._selectionTypeForFailover.ToString()) : null, "selectionTypeForFailover" ,container.Add ); + AddIf( null != this._isStaticIPMigrationEnabled ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isStaticIPMigrationEnabled) : null, "isStaticIpMigrationEnabled" ,container.Add ); + AddIf( null != this._isMacMigrationEnabled ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isMacMigrationEnabled) : null, "isMacMigrationEnabled" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..6f783d7d66c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV to AzStackHCI planned failover model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciplannedFailoverModelCustomPropertiesTypeConverter))] + public partial class HyperVToAzStackHciplannedFailoverModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHciplannedFailoverModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHciplannedFailoverModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHciplannedFailoverModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ShutdownSourceVM")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM = (bool) content.GetValueForProperty("ShutdownSourceVM",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType, 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 HyperVToAzStackHciplannedFailoverModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ShutdownSourceVM")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM = (bool) content.GetValueForProperty("ShutdownSourceVM",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV to AzStackHCI planned failover model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciplannedFailoverModelCustomPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHciplannedFailoverModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..3754da34e38 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHciplannedFailoverModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHciplannedFailoverModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHciplannedFailoverModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHciplannedFailoverModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.cs new file mode 100644 index 00000000000..09382b28609 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI planned failover model custom properties. + public partial class HyperVToAzStackHciplannedFailoverModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties __plannedFailoverModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties(); + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)__plannedFailoverModelCustomProperties).InstanceType = "HyperVToAzStackHCI"; } + + /// Backing field for property. + private bool _shutdownSourceVM; + + /// Gets or sets a value indicating whether VM needs to be shut down. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool ShutdownSourceVM { get => this._shutdownSourceVM; set => this._shutdownSourceVM = value; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHciplannedFailoverModelCustomProperties() + { + this.__plannedFailoverModelCustomProperties.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__plannedFailoverModelCustomProperties), __plannedFailoverModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__plannedFailoverModelCustomProperties), __plannedFailoverModelCustomProperties); + } + } + /// HyperV to AzStackHCI planned failover model custom properties. + public partial interface IHyperVToAzStackHciplannedFailoverModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties + { + /// Gets or sets a value indicating whether VM needs to be shut down. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether VM needs to be shut down.", + SerializedName = @"shutdownSourceVM", + PossibleTypes = new [] { typeof(bool) })] + bool ShutdownSourceVM { get; set; } + + } + /// HyperV to AzStackHCI planned failover model custom properties. + internal partial interface IHyperVToAzStackHciplannedFailoverModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal + { + /// Gets or sets a value indicating whether VM needs to be shut down. + bool ShutdownSourceVM { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.json.cs new file mode 100644 index 00000000000..dc302cc833e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciplannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI planned failover model custom properties. + public partial class HyperVToAzStackHciplannedFailoverModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciplannedFailoverModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHciplannedFailoverModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHciplannedFailoverModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __plannedFailoverModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties(json); + {_shutdownSourceVM = If( json?.PropertyT("shutdownSourceVM"), out var __jsonShutdownSourceVM) ? (bool)__jsonShutdownSourceVM : _shutdownSourceVM;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __plannedFailoverModelCustomProperties?.ToJson(container, serializationMode); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean(this._shutdownSourceVM), "shutdownSourceVM" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..d35d1a40d36 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.PowerShell.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV To AzStackHCI Policy model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcipolicyModelCustomPropertiesTypeConverter))] + public partial class HyperVToAzStackHcipolicyModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHcipolicyModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHcipolicyModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHcipolicyModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RecoveryPointHistoryInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute = (int) content.GetValueForProperty("RecoveryPointHistoryInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("CrashConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute = (int) content.GetValueForProperty("CrashConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("AppConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute = (int) content.GetValueForProperty("AppConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType, 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 HyperVToAzStackHcipolicyModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RecoveryPointHistoryInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute = (int) content.GetValueForProperty("RecoveryPointHistoryInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("CrashConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute = (int) content.GetValueForProperty("CrashConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("AppConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute = (int) content.GetValueForProperty("AppConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV To AzStackHCI Policy model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcipolicyModelCustomPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHcipolicyModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..12efffd06e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHcipolicyModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHcipolicyModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHcipolicyModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHcipolicyModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.cs new file mode 100644 index 00000000000..82ee46829d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV To AzStackHCI Policy model custom properties. + public partial class HyperVToAzStackHcipolicyModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties __policyModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties(); + + /// Backing field for property. + private int _appConsistentFrequencyInMinute; + + /// Gets or sets the app consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int AppConsistentFrequencyInMinute { get => this._appConsistentFrequencyInMinute; set => this._appConsistentFrequencyInMinute = value; } + + /// Backing field for property. + private int _crashConsistentFrequencyInMinute; + + /// Gets or sets the crash consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int CrashConsistentFrequencyInMinute { get => this._crashConsistentFrequencyInMinute; set => this._crashConsistentFrequencyInMinute = value; } + + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)__policyModelCustomProperties).InstanceType = "HyperVToAzStackHCI"; } + + /// Backing field for property. + private int _recoveryPointHistoryInMinute; + + /// + /// Gets or sets the duration in minutes until which the recovery points need to be stored. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int RecoveryPointHistoryInMinute { get => this._recoveryPointHistoryInMinute; set => this._recoveryPointHistoryInMinute = value; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHcipolicyModelCustomProperties() + { + this.__policyModelCustomProperties.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__policyModelCustomProperties), __policyModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__policyModelCustomProperties), __policyModelCustomProperties); + } + } + /// HyperV To AzStackHCI Policy model custom properties. + public partial interface IHyperVToAzStackHcipolicyModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties + { + /// Gets or sets the app consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the app consistent snapshot frequency (in minutes).", + SerializedName = @"appConsistentFrequencyInMinutes", + PossibleTypes = new [] { typeof(int) })] + int AppConsistentFrequencyInMinute { get; set; } + /// Gets or sets the crash consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the crash consistent snapshot frequency (in minutes).", + SerializedName = @"crashConsistentFrequencyInMinutes", + PossibleTypes = new [] { typeof(int) })] + int CrashConsistentFrequencyInMinute { get; set; } + /// + /// Gets or sets the duration in minutes until which the recovery points need to be stored. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the duration in minutes until which the recovery points need to be stored.", + SerializedName = @"recoveryPointHistoryInMinutes", + PossibleTypes = new [] { typeof(int) })] + int RecoveryPointHistoryInMinute { get; set; } + + } + /// HyperV To AzStackHCI Policy model custom properties. + internal partial interface IHyperVToAzStackHcipolicyModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal + { + /// Gets or sets the app consistent snapshot frequency (in minutes). + int AppConsistentFrequencyInMinute { get; set; } + /// Gets or sets the crash consistent snapshot frequency (in minutes). + int CrashConsistentFrequencyInMinute { get; set; } + /// + /// Gets or sets the duration in minutes until which the recovery points need to be stored. + /// + int RecoveryPointHistoryInMinute { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.json.cs new file mode 100644 index 00000000000..5a99c9b2506 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcipolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV To AzStackHCI Policy model custom properties. + public partial class HyperVToAzStackHcipolicyModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcipolicyModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHcipolicyModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHcipolicyModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __policyModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties(json); + {_recoveryPointHistoryInMinute = If( json?.PropertyT("recoveryPointHistoryInMinutes"), out var __jsonRecoveryPointHistoryInMinutes) ? (int)__jsonRecoveryPointHistoryInMinutes : _recoveryPointHistoryInMinute;} + {_crashConsistentFrequencyInMinute = If( json?.PropertyT("crashConsistentFrequencyInMinutes"), out var __jsonCrashConsistentFrequencyInMinutes) ? (int)__jsonCrashConsistentFrequencyInMinutes : _crashConsistentFrequencyInMinute;} + {_appConsistentFrequencyInMinute = If( json?.PropertyT("appConsistentFrequencyInMinutes"), out var __jsonAppConsistentFrequencyInMinutes) ? (int)__jsonAppConsistentFrequencyInMinutes : _appConsistentFrequencyInMinute;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __policyModelCustomProperties?.ToJson(container, serializationMode); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._recoveryPointHistoryInMinute), "recoveryPointHistoryInMinutes" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._crashConsistentFrequencyInMinute), "crashConsistentFrequencyInMinutes" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._appConsistentFrequencyInMinute), "appConsistentFrequencyInMinutes" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.PowerShell.cs new file mode 100644 index 00000000000..dc424fdd489 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.PowerShell.cs @@ -0,0 +1,271 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperVToAzStackHCI protected disk properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedDiskPropertiesTypeConverter))] + public partial class HyperVToAzStackHciprotectedDiskProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHciprotectedDiskProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHciprotectedDiskProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHciprotectedDiskProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerLocalPath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath = (string) content.GetValueForProperty("StorageContainerLocalPath",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId = (string) content.GetValueForProperty("SourceDiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName = (string) content.GetValueForProperty("SourceDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName, global::System.Convert.ToString); + } + if (content.Contains("SeedDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName = (string) content.GetValueForProperty("SeedDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName, global::System.Convert.ToString); + } + if (content.Contains("TestMigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName = (string) content.GetValueForProperty("TestMigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("MigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName = (string) content.GetValueForProperty("MigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk = (bool?) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CapacityInByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte = (long?) content.GetValueForProperty("CapacityInByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskType = (string) content.GetValueForProperty("DiskType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskType, global::System.Convert.ToString); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize, (__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 HyperVToAzStackHciprotectedDiskProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerLocalPath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath = (string) content.GetValueForProperty("StorageContainerLocalPath",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId = (string) content.GetValueForProperty("SourceDiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName = (string) content.GetValueForProperty("SourceDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName, global::System.Convert.ToString); + } + if (content.Contains("SeedDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName = (string) content.GetValueForProperty("SeedDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName, global::System.Convert.ToString); + } + if (content.Contains("TestMigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName = (string) content.GetValueForProperty("TestMigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("MigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName = (string) content.GetValueForProperty("MigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk = (bool?) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CapacityInByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte = (long?) content.GetValueForProperty("CapacityInByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskType = (string) content.GetValueForProperty("DiskType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskType, global::System.Convert.ToString); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperVToAzStackHCI protected disk properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedDiskPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHciprotectedDiskProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.TypeConverter.cs new file mode 100644 index 00000000000..4c1644019bf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHciprotectedDiskPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHciprotectedDiskProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedDiskProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedDiskProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.cs new file mode 100644 index 00000000000..631e14209de --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.cs @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStackHCI protected disk properties. + public partial class HyperVToAzStackHciprotectedDiskProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal + { + + /// Backing field for property. + private long? _capacityInByte; + + /// Gets or sets the disk capacity in bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? CapacityInByte { get => this._capacityInByte; } + + /// Backing field for property. + private long? _diskBlockSize; + + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskBlockSize { get => this._diskBlockSize; } + + /// Backing field for property. + private long? _diskLogicalSectorSize; + + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskLogicalSectorSize { get => this._diskLogicalSectorSize; } + + /// Backing field for property. + private long? _diskPhysicalSectorSize; + + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskPhysicalSectorSize { get => this._diskPhysicalSectorSize; } + + /// Backing field for property. + private string _diskType; + + /// Gets or sets the disk type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskType { get => this._diskType; } + + /// Backing field for property. + private bool? _isDynamic; + + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamic { get => this._isDynamic; } + + /// Backing field for property. + private bool? _isOSDisk; + + /// Gets or sets a value indicating whether the disk is the OS disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsOSDisk { get => this._isOSDisk; } + + /// Internal Acessors for CapacityInByte + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.CapacityInByte { get => this._capacityInByte; set { {_capacityInByte = value;} } } + + /// Internal Acessors for DiskBlockSize + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.DiskBlockSize { get => this._diskBlockSize; set { {_diskBlockSize = value;} } } + + /// Internal Acessors for DiskLogicalSectorSize + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.DiskLogicalSectorSize { get => this._diskLogicalSectorSize; set { {_diskLogicalSectorSize = value;} } } + + /// Internal Acessors for DiskPhysicalSectorSize + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.DiskPhysicalSectorSize { get => this._diskPhysicalSectorSize; set { {_diskPhysicalSectorSize = value;} } } + + /// Internal Acessors for DiskType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.DiskType { get => this._diskType; set { {_diskType = value;} } } + + /// Internal Acessors for IsDynamic + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.IsDynamic { get => this._isDynamic; set { {_isDynamic = value;} } } + + /// Internal Acessors for IsOSDisk + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.IsOSDisk { get => this._isOSDisk; set { {_isOSDisk = value;} } } + + /// Internal Acessors for MigrateDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.MigrateDiskName { get => this._migrateDiskName; set { {_migrateDiskName = value;} } } + + /// Internal Acessors for SeedDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.SeedDiskName { get => this._seedDiskName; set { {_seedDiskName = value;} } } + + /// Internal Acessors for SourceDiskId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.SourceDiskId { get => this._sourceDiskId; set { {_sourceDiskId = value;} } } + + /// Internal Acessors for SourceDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.SourceDiskName { get => this._sourceDiskName; set { {_sourceDiskName = value;} } } + + /// Internal Acessors for StorageContainerId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.StorageContainerId { get => this._storageContainerId; set { {_storageContainerId = value;} } } + + /// Internal Acessors for StorageContainerLocalPath + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.StorageContainerLocalPath { get => this._storageContainerLocalPath; set { {_storageContainerLocalPath = value;} } } + + /// Internal Acessors for TestMigrateDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskPropertiesInternal.TestMigrateDiskName { get => this._testMigrateDiskName; set { {_testMigrateDiskName = value;} } } + + /// Backing field for property. + private string _migrateDiskName; + + /// Gets or sets the failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrateDiskName { get => this._migrateDiskName; } + + /// Backing field for property. + private string _seedDiskName; + + /// Gets or sets the seed disk name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SeedDiskName { get => this._seedDiskName; } + + /// Backing field for property. + private string _sourceDiskId; + + /// Gets or sets the source disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceDiskId { get => this._sourceDiskId; } + + /// Backing field for property. + private string _sourceDiskName; + + /// Gets or sets the source disk Name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceDiskName { get => this._sourceDiskName; } + + /// Backing field for property. + private string _storageContainerId; + + /// Gets or sets the ARM Id of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerId { get => this._storageContainerId; } + + /// Backing field for property. + private string _storageContainerLocalPath; + + /// Gets or sets the local path of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerLocalPath { get => this._storageContainerLocalPath; } + + /// Backing field for property. + private string _testMigrateDiskName; + + /// Gets or sets the test failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestMigrateDiskName { get => this._testMigrateDiskName; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHciprotectedDiskProperties() + { + + } + } + /// HyperVToAzStackHCI protected disk properties. + public partial interface IHyperVToAzStackHciprotectedDiskProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the disk capacity in bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the disk capacity in bytes.", + SerializedName = @"capacityInBytes", + PossibleTypes = new [] { typeof(long) })] + long? CapacityInByte { get; } + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value of disk block size.", + SerializedName = @"diskBlockSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskBlockSize { get; } + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value of disk logical sector size.", + SerializedName = @"diskLogicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskLogicalSectorSize { get; } + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value of disk physical sector size.", + SerializedName = @"diskPhysicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskPhysicalSectorSize { get; } + /// Gets or sets the disk type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the disk type.", + SerializedName = @"diskType", + PossibleTypes = new [] { typeof(string) })] + string DiskType { get; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk.", + SerializedName = @"isDynamic", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamic { get; } + /// Gets or sets a value indicating whether the disk is the OS disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether the disk is the OS disk.", + SerializedName = @"isOsDisk", + PossibleTypes = new [] { typeof(bool) })] + bool? IsOSDisk { get; } + /// Gets or sets the failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the failover clone disk.", + SerializedName = @"migrateDiskName", + PossibleTypes = new [] { typeof(string) })] + string MigrateDiskName { get; } + /// Gets or sets the seed disk name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the seed disk name.", + SerializedName = @"seedDiskName", + PossibleTypes = new [] { typeof(string) })] + string SeedDiskName { get; } + /// Gets or sets the source disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source disk Id.", + SerializedName = @"sourceDiskId", + PossibleTypes = new [] { typeof(string) })] + string SourceDiskId { get; } + /// Gets or sets the source disk Name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source disk Name.", + SerializedName = @"sourceDiskName", + PossibleTypes = new [] { typeof(string) })] + string SourceDiskName { get; } + /// Gets or sets the ARM Id of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the ARM Id of the storage container.", + SerializedName = @"storageContainerId", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerId { get; } + /// Gets or sets the local path of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the local path of the storage container.", + SerializedName = @"storageContainerLocalPath", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerLocalPath { get; } + /// Gets or sets the test failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test failover clone disk.", + SerializedName = @"testMigrateDiskName", + PossibleTypes = new [] { typeof(string) })] + string TestMigrateDiskName { get; } + + } + /// HyperVToAzStackHCI protected disk properties. + internal partial interface IHyperVToAzStackHciprotectedDiskPropertiesInternal + + { + /// Gets or sets the disk capacity in bytes. + long? CapacityInByte { get; set; } + /// Gets or sets a value of disk block size. + long? DiskBlockSize { get; set; } + /// Gets or sets a value of disk logical sector size. + long? DiskLogicalSectorSize { get; set; } + /// Gets or sets a value of disk physical sector size. + long? DiskPhysicalSectorSize { get; set; } + /// Gets or sets the disk type. + string DiskType { get; set; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + bool? IsDynamic { get; set; } + /// Gets or sets a value indicating whether the disk is the OS disk. + bool? IsOSDisk { get; set; } + /// Gets or sets the failover clone disk. + string MigrateDiskName { get; set; } + /// Gets or sets the seed disk name. + string SeedDiskName { get; set; } + /// Gets or sets the source disk Id. + string SourceDiskId { get; set; } + /// Gets or sets the source disk Name. + string SourceDiskName { get; set; } + /// Gets or sets the ARM Id of the storage container. + string StorageContainerId { get; set; } + /// Gets or sets the local path of the storage container. + string StorageContainerLocalPath { get; set; } + /// Gets or sets the test failover clone disk. + string TestMigrateDiskName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.json.cs new file mode 100644 index 00000000000..4391367acdf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedDiskProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStackHCI protected disk properties. + public partial class HyperVToAzStackHciprotectedDiskProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHciprotectedDiskProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHciprotectedDiskProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_storageContainerId = If( json?.PropertyT("storageContainerId"), out var __jsonStorageContainerId) ? (string)__jsonStorageContainerId : (string)_storageContainerId;} + {_storageContainerLocalPath = If( json?.PropertyT("storageContainerLocalPath"), out var __jsonStorageContainerLocalPath) ? (string)__jsonStorageContainerLocalPath : (string)_storageContainerLocalPath;} + {_sourceDiskId = If( json?.PropertyT("sourceDiskId"), out var __jsonSourceDiskId) ? (string)__jsonSourceDiskId : (string)_sourceDiskId;} + {_sourceDiskName = If( json?.PropertyT("sourceDiskName"), out var __jsonSourceDiskName) ? (string)__jsonSourceDiskName : (string)_sourceDiskName;} + {_seedDiskName = If( json?.PropertyT("seedDiskName"), out var __jsonSeedDiskName) ? (string)__jsonSeedDiskName : (string)_seedDiskName;} + {_testMigrateDiskName = If( json?.PropertyT("testMigrateDiskName"), out var __jsonTestMigrateDiskName) ? (string)__jsonTestMigrateDiskName : (string)_testMigrateDiskName;} + {_migrateDiskName = If( json?.PropertyT("migrateDiskName"), out var __jsonMigrateDiskName) ? (string)__jsonMigrateDiskName : (string)_migrateDiskName;} + {_isOSDisk = If( json?.PropertyT("isOsDisk"), out var __jsonIsOSDisk) ? (bool?)__jsonIsOSDisk : _isOSDisk;} + {_capacityInByte = If( json?.PropertyT("capacityInBytes"), out var __jsonCapacityInBytes) ? (long?)__jsonCapacityInBytes : _capacityInByte;} + {_isDynamic = If( json?.PropertyT("isDynamic"), out var __jsonIsDynamic) ? (bool?)__jsonIsDynamic : _isDynamic;} + {_diskType = If( json?.PropertyT("diskType"), out var __jsonDiskType) ? (string)__jsonDiskType : (string)_diskType;} + {_diskBlockSize = If( json?.PropertyT("diskBlockSize"), out var __jsonDiskBlockSize) ? (long?)__jsonDiskBlockSize : _diskBlockSize;} + {_diskLogicalSectorSize = If( json?.PropertyT("diskLogicalSectorSize"), out var __jsonDiskLogicalSectorSize) ? (long?)__jsonDiskLogicalSectorSize : _diskLogicalSectorSize;} + {_diskPhysicalSectorSize = If( json?.PropertyT("diskPhysicalSectorSize"), out var __jsonDiskPhysicalSectorSize) ? (long?)__jsonDiskPhysicalSectorSize : _diskPhysicalSectorSize;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._storageContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerId.ToString()) : null, "storageContainerId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._storageContainerLocalPath)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerLocalPath.ToString()) : null, "storageContainerLocalPath" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceDiskId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceDiskId.ToString()) : null, "sourceDiskId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceDiskName.ToString()) : null, "sourceDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._seedDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._seedDiskName.ToString()) : null, "seedDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testMigrateDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testMigrateDiskName.ToString()) : null, "testMigrateDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._migrateDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrateDiskName.ToString()) : null, "migrateDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isOSDisk ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isOSDisk) : null, "isOsDisk" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._capacityInByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._capacityInByte) : null, "capacityInBytes" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDynamic ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamic) : null, "isDynamic" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._diskType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskType.ToString()) : null, "diskType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._diskBlockSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskBlockSize) : null, "diskBlockSize" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._diskLogicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskLogicalSectorSize) : null, "diskLogicalSectorSize" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._diskPhysicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskPhysicalSectorSize) : null, "diskPhysicalSectorSize" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..ed4a8a8a88a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.PowerShell.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedItemModelCustomPropertiesTypeConverter))] + public partial class HyperVToAzStackHciprotectedItemModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHciprotectedItemModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHciprotectedItemModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHciprotectedItemModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("ActiveLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation = (string) content.GetValueForProperty("ActiveLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation, global::System.Convert.ToString); + } + if (content.Contains("TargetHciClusterId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId = (string) content.GetValueForProperty("TargetHciClusterId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId, global::System.Convert.ToString); + } + if (content.Contains("TargetArcClusterCustomLocationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId = (string) content.GetValueForProperty("TargetArcClusterCustomLocationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId, global::System.Convert.ToString); + } + if (content.Contains("TargetAzStackHciClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName = (string) content.GetValueForProperty("TargetAzStackHciClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName, global::System.Convert.ToString); + } + if (content.Contains("FabricDiscoveryMachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId = (string) content.GetValueForProperty("FabricDiscoveryMachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId, global::System.Convert.ToString); + } + if (content.Contains("DisksToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude = (System.Collections.Generic.List) content.GetValueForProperty("DisksToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcidiskInputTypeConverter.ConvertFrom)); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("SourceVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName = (string) content.GetValueForProperty("SourceVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName, global::System.Convert.ToString); + } + if (content.Contains("SourceCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore = (int?) content.GetValueForProperty("SourceCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SourceMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte = (double?) content.GetValueForProperty("SourceMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte, (__y)=> (double) global::System.Convert.ChangeType(__y, typeof(double))); + } + if (content.Contains("TargetVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName = (string) content.GetValueForProperty("TargetVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceGroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId = (string) content.GetValueForProperty("TargetResourceGroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("HyperVGeneration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration = (string) content.GetValueForProperty("HyperVGeneration",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("RunAsAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId = (string) content.GetValueForProperty("RunAsAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName = (string) content.GetValueForProperty("SourceFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName = (string) content.GetValueForProperty("TargetFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("OSName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName = (string) content.GetValueForProperty("OSName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName, global::System.Convert.ToString); + } + if (content.Contains("FirmwareType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType = (string) content.GetValueForProperty("FirmwareType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType, global::System.Convert.ToString); + } + if (content.Contains("TargetLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation = (string) content.GetValueForProperty("TargetLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation, global::System.Convert.ToString); + } + if (content.Contains("CustomLocationRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion = (string) content.GetValueForProperty("CustomLocationRegion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion, global::System.Convert.ToString); + } + if (content.Contains("FailoverRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId = (string) content.GetValueForProperty("FailoverRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("LastRecoveryPointReceived")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived = (global::System.DateTime?) content.GetValueForProperty("LastRecoveryPointReceived",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId = (string) content.GetValueForProperty("LastRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("InitialReplicationProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage = (int?) content.GetValueForProperty("InitialReplicationProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResyncProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage = (int?) content.GetValueForProperty("ResyncProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ProtectedDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHciprotectedDiskPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("ProtectedNic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedNic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHciprotectedNicPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetVMBiosId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId = (string) content.GetValueForProperty("TargetVMBiosId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId, global::System.Convert.ToString); + } + if (content.Contains("LastReplicationUpdateTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime = (global::System.DateTime?) content.GetValueForProperty("LastReplicationUpdateTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__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 HyperVToAzStackHciprotectedItemModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("ActiveLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation = (string) content.GetValueForProperty("ActiveLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation, global::System.Convert.ToString); + } + if (content.Contains("TargetHciClusterId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId = (string) content.GetValueForProperty("TargetHciClusterId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId, global::System.Convert.ToString); + } + if (content.Contains("TargetArcClusterCustomLocationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId = (string) content.GetValueForProperty("TargetArcClusterCustomLocationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId, global::System.Convert.ToString); + } + if (content.Contains("TargetAzStackHciClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName = (string) content.GetValueForProperty("TargetAzStackHciClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName, global::System.Convert.ToString); + } + if (content.Contains("FabricDiscoveryMachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId = (string) content.GetValueForProperty("FabricDiscoveryMachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId, global::System.Convert.ToString); + } + if (content.Contains("DisksToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude = (System.Collections.Generic.List) content.GetValueForProperty("DisksToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcidiskInputTypeConverter.ConvertFrom)); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("SourceVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName = (string) content.GetValueForProperty("SourceVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName, global::System.Convert.ToString); + } + if (content.Contains("SourceCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore = (int?) content.GetValueForProperty("SourceCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SourceMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte = (double?) content.GetValueForProperty("SourceMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte, (__y)=> (double) global::System.Convert.ChangeType(__y, typeof(double))); + } + if (content.Contains("TargetVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName = (string) content.GetValueForProperty("TargetVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceGroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId = (string) content.GetValueForProperty("TargetResourceGroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("HyperVGeneration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration = (string) content.GetValueForProperty("HyperVGeneration",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("RunAsAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId = (string) content.GetValueForProperty("RunAsAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName = (string) content.GetValueForProperty("SourceFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName = (string) content.GetValueForProperty("TargetFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("OSName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName = (string) content.GetValueForProperty("OSName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName, global::System.Convert.ToString); + } + if (content.Contains("FirmwareType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType = (string) content.GetValueForProperty("FirmwareType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType, global::System.Convert.ToString); + } + if (content.Contains("TargetLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation = (string) content.GetValueForProperty("TargetLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation, global::System.Convert.ToString); + } + if (content.Contains("CustomLocationRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion = (string) content.GetValueForProperty("CustomLocationRegion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion, global::System.Convert.ToString); + } + if (content.Contains("FailoverRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId = (string) content.GetValueForProperty("FailoverRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("LastRecoveryPointReceived")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived = (global::System.DateTime?) content.GetValueForProperty("LastRecoveryPointReceived",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId = (string) content.GetValueForProperty("LastRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("InitialReplicationProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage = (int?) content.GetValueForProperty("InitialReplicationProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResyncProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage = (int?) content.GetValueForProperty("ResyncProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ProtectedDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHciprotectedDiskPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("ProtectedNic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedNic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHciprotectedNicPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetVMBiosId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId = (string) content.GetValueForProperty("TargetVMBiosId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId, global::System.Convert.ToString); + } + if (content.Contains("LastReplicationUpdateTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime = (global::System.DateTime?) content.GetValueForProperty("LastReplicationUpdateTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedItemModelCustomPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHciprotectedItemModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..dc210277fdb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHciprotectedItemModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHciprotectedItemModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedItemModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedItemModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.cs new file mode 100644 index 00000000000..a869ec6c6bd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.cs @@ -0,0 +1,961 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI Protected item model custom properties. + public partial class HyperVToAzStackHciprotectedItemModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties __protectedItemModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties(); + + /// Backing field for property. + private string _activeLocation; + + /// Gets or sets the location of the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ActiveLocation { get => this._activeLocation; } + + /// Backing field for property. + private string _customLocationRegion; + + /// Gets or sets the location of Azure Arc HCI custom location resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string CustomLocationRegion { get => this._customLocationRegion; set => this._customLocationRegion = value; } + + /// Backing field for property. + private System.Collections.Generic.List _disksToInclude; + + /// Gets or sets the list of disks to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List DisksToInclude { get => this._disksToInclude; set => this._disksToInclude = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig _dynamicMemoryConfig; + + /// Protected item dynamic memory config. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set => this._dynamicMemoryConfig = value; } + + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMaximumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMinimumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DynamicMemoryConfigTargetMemoryBufferPercentage { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage = value ?? default(int); } + + /// Backing field for property. + private string _fabricDiscoveryMachineId; + + /// Gets or sets the ARM Id of the discovered machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricDiscoveryMachineId { get => this._fabricDiscoveryMachineId; set => this._fabricDiscoveryMachineId = value; } + + /// Backing field for property. + private string _failoverRecoveryPointId; + + /// Gets or sets the recovery point Id to which the VM was failed over. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FailoverRecoveryPointId { get => this._failoverRecoveryPointId; } + + /// Backing field for property. + private string _firmwareType; + + /// Gets or sets the firmware type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FirmwareType { get => this._firmwareType; } + + /// Backing field for property. + private string _hyperVGeneration; + + /// Gets or sets the hypervisor generation of the virtual machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HyperVGeneration { get => this._hyperVGeneration; set => this._hyperVGeneration = value; } + + /// Backing field for property. + private int? _initialReplicationProgressPercentage; + + /// + /// Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks + /// in the source VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? InitialReplicationProgressPercentage { get => this._initialReplicationProgressPercentage; } + + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)__protectedItemModelCustomProperties).InstanceType = "HyperVToAzStackHCI"; } + + /// Backing field for property. + private bool? _isDynamicRam; + + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamicRam { get => this._isDynamicRam; set => this._isDynamicRam = value; } + + /// Backing field for property. + private string _lastRecoveryPointId; + + /// Gets or sets the last recovery point Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string LastRecoveryPointId { get => this._lastRecoveryPointId; } + + /// Backing field for property. + private global::System.DateTime? _lastRecoveryPointReceived; + + /// Gets or sets the last recovery point received time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastRecoveryPointReceived { get => this._lastRecoveryPointReceived; } + + /// Backing field for property. + private global::System.DateTime? _lastReplicationUpdateTime; + + /// Gets or sets the latest timestamp that replication status is updated. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastReplicationUpdateTime { get => this._lastReplicationUpdateTime; } + + /// Internal Acessors for ActiveLocation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.ActiveLocation { get => this._activeLocation; set { {_activeLocation = value;} } } + + /// Internal Acessors for DynamicMemoryConfig + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set { {_dynamicMemoryConfig = value;} } } + + /// Internal Acessors for FailoverRecoveryPointId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.FailoverRecoveryPointId { get => this._failoverRecoveryPointId; set { {_failoverRecoveryPointId = value;} } } + + /// Internal Acessors for FirmwareType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.FirmwareType { get => this._firmwareType; set { {_firmwareType = value;} } } + + /// Internal Acessors for InitialReplicationProgressPercentage + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.InitialReplicationProgressPercentage { get => this._initialReplicationProgressPercentage; set { {_initialReplicationProgressPercentage = value;} } } + + /// Internal Acessors for LastRecoveryPointId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.LastRecoveryPointId { get => this._lastRecoveryPointId; set { {_lastRecoveryPointId = value;} } } + + /// Internal Acessors for LastRecoveryPointReceived + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.LastRecoveryPointReceived { get => this._lastRecoveryPointReceived; set { {_lastRecoveryPointReceived = value;} } } + + /// Internal Acessors for LastReplicationUpdateTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.LastReplicationUpdateTime { get => this._lastReplicationUpdateTime; set { {_lastReplicationUpdateTime = value;} } } + + /// Internal Acessors for OSName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.OSName { get => this._oSName; set { {_oSName = value;} } } + + /// Internal Acessors for OSType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.OSType { get => this._oSType; set { {_oSType = value;} } } + + /// Internal Acessors for ProtectedDisk + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.ProtectedDisk { get => this._protectedDisk; set { {_protectedDisk = value;} } } + + /// Internal Acessors for ProtectedNic + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.ProtectedNic { get => this._protectedNic; set { {_protectedNic = value;} } } + + /// Internal Acessors for ResyncProgressPercentage + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.ResyncProgressPercentage { get => this._resyncProgressPercentage; set { {_resyncProgressPercentage = value;} } } + + /// Internal Acessors for SourceApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceApplianceName { get => this._sourceApplianceName; set { {_sourceApplianceName = value;} } } + + /// Internal Acessors for SourceCpuCore + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceCpuCore { get => this._sourceCpuCore; set { {_sourceCpuCore = value;} } } + + /// Internal Acessors for SourceMemoryInMegaByte + double? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceMemoryInMegaByte { get => this._sourceMemoryInMegaByte; set { {_sourceMemoryInMegaByte = value;} } } + + /// Internal Acessors for SourceVMName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceVMName { get => this._sourceVMName; set { {_sourceVMName = value;} } } + + /// Internal Acessors for TargetApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetApplianceName { get => this._targetApplianceName; set { {_targetApplianceName = value;} } } + + /// Internal Acessors for TargetAzStackHciClusterName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetAzStackHciClusterName { get => this._targetAzStackHciClusterName; set { {_targetAzStackHciClusterName = value;} } } + + /// Internal Acessors for TargetLocation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetLocation { get => this._targetLocation; set { {_targetLocation = value;} } } + + /// Internal Acessors for TargetVMBiosId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetVMBiosId { get => this._targetVMBiosId; set { {_targetVMBiosId = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _nicsToInclude; + + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List NicsToInclude { get => this._nicsToInclude; set => this._nicsToInclude = value; } + + /// Backing field for property. + private string _oSName; + + /// Gets or sets the name of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OSName { get => this._oSName; } + + /// Backing field for property. + private string _oSType; + + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OSType { get => this._oSType; } + + /// Backing field for property. + private System.Collections.Generic.List _protectedDisk; + + /// Gets or sets the list of protected disks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ProtectedDisk { get => this._protectedDisk; } + + /// Backing field for property. + private System.Collections.Generic.List _protectedNic; + + /// Gets or sets the VM NIC details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ProtectedNic { get => this._protectedNic; } + + /// Backing field for property. + private int? _resyncProgressPercentage; + + /// + /// Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source + /// VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? ResyncProgressPercentage { get => this._resyncProgressPercentage; } + + /// Backing field for property. + private string _runAsAccountId; + + /// Gets or sets the Run As account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RunAsAccountId { get => this._runAsAccountId; set => this._runAsAccountId = value; } + + /// Backing field for property. + private string _sourceApplianceName; + + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceApplianceName { get => this._sourceApplianceName; } + + /// Backing field for property. + private int? _sourceCpuCore; + + /// Gets or sets the source VM CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? SourceCpuCore { get => this._sourceCpuCore; } + + /// Backing field for property. + private string _sourceFabricAgentName; + + /// Gets or sets the source fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceFabricAgentName { get => this._sourceFabricAgentName; set => this._sourceFabricAgentName = value; } + + /// Backing field for property. + private double? _sourceMemoryInMegaByte; + + /// Gets or sets the source VM ram memory size in megabytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public double? SourceMemoryInMegaByte { get => this._sourceMemoryInMegaByte; } + + /// Backing field for property. + private string _sourceVMName; + + /// Gets or sets the source VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceVMName { get => this._sourceVMName; } + + /// Backing field for property. + private string _storageContainerId; + + /// Gets or sets the target storage container ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerId { get => this._storageContainerId; set => this._storageContainerId = value; } + + /// Backing field for property. + private string _targetApplianceName; + + /// Gets or sets the target appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetApplianceName { get => this._targetApplianceName; } + + /// Backing field for property. + private string _targetArcClusterCustomLocationId; + + /// Gets or sets the Target Arc Cluster Custom Location ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetArcClusterCustomLocationId { get => this._targetArcClusterCustomLocationId; set => this._targetArcClusterCustomLocationId = value; } + + /// Backing field for property. + private string _targetAzStackHciClusterName; + + /// Gets or sets the Target AzStackHCI cluster name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetAzStackHciClusterName { get => this._targetAzStackHciClusterName; } + + /// Backing field for property. + private int? _targetCpuCore; + + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetCpuCore { get => this._targetCpuCore; set => this._targetCpuCore = value; } + + /// Backing field for property. + private string _targetFabricAgentName; + + /// Gets or sets the target fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetFabricAgentName { get => this._targetFabricAgentName; set => this._targetFabricAgentName = value; } + + /// Backing field for property. + private string _targetHciClusterId; + + /// Gets or sets the Target HCI Cluster ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetHciClusterId { get => this._targetHciClusterId; set => this._targetHciClusterId = value; } + + /// Backing field for property. + private string _targetLocation; + + /// Gets or sets the target location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetLocation { get => this._targetLocation; } + + /// Backing field for property. + private int? _targetMemoryInMegaByte; + + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetMemoryInMegaByte { get => this._targetMemoryInMegaByte; set => this._targetMemoryInMegaByte = value; } + + /// Backing field for property. + private string _targetNetworkId; + + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetNetworkId { get => this._targetNetworkId; set => this._targetNetworkId = value; } + + /// Backing field for property. + private string _targetResourceGroupId; + + /// Gets or sets the target resource group ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetResourceGroupId { get => this._targetResourceGroupId; set => this._targetResourceGroupId = value; } + + /// Backing field for property. + private string _targetVMBiosId; + + /// Gets or sets the BIOS Id of the target AzStackHCI VM. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetVMBiosId { get => this._targetVMBiosId; } + + /// Backing field for property. + private string _targetVMName; + + /// Gets or sets the target VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetVMName { get => this._targetVMName; set => this._targetVMName = value; } + + /// Backing field for property. + private string _testNetworkId; + + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestNetworkId { get => this._testNetworkId; set => this._testNetworkId = value; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHciprotectedItemModelCustomProperties() + { + this.__protectedItemModelCustomProperties.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__protectedItemModelCustomProperties), __protectedItemModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__protectedItemModelCustomProperties), __protectedItemModelCustomProperties); + } + } + /// HyperV to AzStackHCI Protected item model custom properties. + public partial interface IHyperVToAzStackHciprotectedItemModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties + { + /// Gets or sets the location of the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the location of the protected item.", + SerializedName = @"activeLocation", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Primary", "Recovery")] + string ActiveLocation { get; } + /// Gets or sets the location of Azure Arc HCI custom location resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the location of Azure Arc HCI custom location resource.", + SerializedName = @"customLocationRegion", + PossibleTypes = new [] { typeof(string) })] + string CustomLocationRegion { get; set; } + /// Gets or sets the list of disks to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of disks to replicate.", + SerializedName = @"disksToInclude", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput) })] + System.Collections.Generic.List DisksToInclude { get; set; } + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets maximum memory in MB.", + SerializedName = @"maximumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets minimum memory in MB.", + SerializedName = @"minimumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets target memory buffer in %.", + SerializedName = @"targetMemoryBufferPercentage", + PossibleTypes = new [] { typeof(int) })] + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets the ARM Id of the discovered machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the discovered machine.", + SerializedName = @"fabricDiscoveryMachineId", + PossibleTypes = new [] { typeof(string) })] + string FabricDiscoveryMachineId { get; set; } + /// Gets or sets the recovery point Id to which the VM was failed over. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the recovery point Id to which the VM was failed over.", + SerializedName = @"failoverRecoveryPointId", + PossibleTypes = new [] { typeof(string) })] + string FailoverRecoveryPointId { get; } + /// Gets or sets the firmware type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the firmware type.", + SerializedName = @"firmwareType", + PossibleTypes = new [] { typeof(string) })] + string FirmwareType { get; } + /// Gets or sets the hypervisor generation of the virtual machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the hypervisor generation of the virtual machine.", + SerializedName = @"hyperVGeneration", + PossibleTypes = new [] { typeof(string) })] + string HyperVGeneration { get; set; } + /// + /// Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks + /// in the source VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks in the source VM.", + SerializedName = @"initialReplicationProgressPercentage", + PossibleTypes = new [] { typeof(int) })] + int? InitialReplicationProgressPercentage { get; } + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether memory is dynamical.", + SerializedName = @"isDynamicRam", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamicRam { get; set; } + /// Gets or sets the last recovery point Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the last recovery point Id.", + SerializedName = @"lastRecoveryPointId", + PossibleTypes = new [] { typeof(string) })] + string LastRecoveryPointId { get; } + /// Gets or sets the last recovery point received time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the last recovery point received time.", + SerializedName = @"lastRecoveryPointReceived", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastRecoveryPointReceived { get; } + /// Gets or sets the latest timestamp that replication status is updated. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the latest timestamp that replication status is updated.", + SerializedName = @"lastReplicationUpdateTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastReplicationUpdateTime { get; } + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of VM NIC to replicate.", + SerializedName = @"nicsToInclude", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput) })] + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the name of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the name of the OS.", + SerializedName = @"osName", + PossibleTypes = new [] { typeof(string) })] + string OSName { get; } + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the type of the OS.", + SerializedName = @"osType", + PossibleTypes = new [] { typeof(string) })] + string OSType { get; } + /// Gets or sets the list of protected disks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of protected disks.", + SerializedName = @"protectedDisks", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties) })] + System.Collections.Generic.List ProtectedDisk { get; } + /// Gets or sets the VM NIC details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the VM NIC details.", + SerializedName = @"protectedNics", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties) })] + System.Collections.Generic.List ProtectedNic { get; } + /// + /// Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source + /// VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source VM.", + SerializedName = @"resyncProgressPercentage", + PossibleTypes = new [] { typeof(int) })] + int? ResyncProgressPercentage { get; } + /// Gets or sets the Run As account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Run As account Id.", + SerializedName = @"runAsAccountId", + PossibleTypes = new [] { typeof(string) })] + string RunAsAccountId { get; set; } + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source appliance name.", + SerializedName = @"sourceApplianceName", + PossibleTypes = new [] { typeof(string) })] + string SourceApplianceName { get; } + /// Gets or sets the source VM CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source VM CPU cores.", + SerializedName = @"sourceCpuCores", + PossibleTypes = new [] { typeof(int) })] + int? SourceCpuCore { get; } + /// Gets or sets the source fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the source fabric agent name.", + SerializedName = @"sourceFabricAgentName", + PossibleTypes = new [] { typeof(string) })] + string SourceFabricAgentName { get; set; } + /// Gets or sets the source VM ram memory size in megabytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source VM ram memory size in megabytes.", + SerializedName = @"sourceMemoryInMegaBytes", + PossibleTypes = new [] { typeof(double) })] + double? SourceMemoryInMegaByte { get; } + /// Gets or sets the source VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source VM display name.", + SerializedName = @"sourceVmName", + PossibleTypes = new [] { typeof(string) })] + string SourceVMName { get; } + /// Gets or sets the target storage container ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target storage container ARM Id.", + SerializedName = @"storageContainerId", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerId { get; set; } + /// Gets or sets the target appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target appliance name.", + SerializedName = @"targetApplianceName", + PossibleTypes = new [] { typeof(string) })] + string TargetApplianceName { get; } + /// Gets or sets the Target Arc Cluster Custom Location ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Target Arc Cluster Custom Location ARM Id.", + SerializedName = @"targetArcClusterCustomLocationId", + PossibleTypes = new [] { typeof(string) })] + string TargetArcClusterCustomLocationId { get; set; } + /// Gets or sets the Target AzStackHCI cluster name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Target AzStackHCI cluster name.", + SerializedName = @"targetAzStackHciClusterName", + PossibleTypes = new [] { typeof(string) })] + string TargetAzStackHciClusterName { get; } + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target CPU cores.", + SerializedName = @"targetCpuCores", + PossibleTypes = new [] { typeof(int) })] + int? TargetCpuCore { get; set; } + /// Gets or sets the target fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target fabric agent name.", + SerializedName = @"targetFabricAgentName", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricAgentName { get; set; } + /// Gets or sets the Target HCI Cluster ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Target HCI Cluster ARM Id.", + SerializedName = @"targetHciClusterId", + PossibleTypes = new [] { typeof(string) })] + string TargetHciClusterId { get; set; } + /// Gets or sets the target location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target location.", + SerializedName = @"targetLocation", + PossibleTypes = new [] { typeof(string) })] + string TargetLocation { get; } + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target memory in mega-bytes.", + SerializedName = @"targetMemoryInMegaBytes", + PossibleTypes = new [] { typeof(int) })] + int? TargetMemoryInMegaByte { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target network Id within AzStackHCI Cluster.", + SerializedName = @"targetNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TargetNetworkId { get; set; } + /// Gets or sets the target resource group ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target resource group ARM Id.", + SerializedName = @"targetResourceGroupId", + PossibleTypes = new [] { typeof(string) })] + string TargetResourceGroupId { get; set; } + /// Gets or sets the BIOS Id of the target AzStackHCI VM. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the BIOS Id of the target AzStackHCI VM.", + SerializedName = @"targetVmBiosId", + PossibleTypes = new [] { typeof(string) })] + string TargetVMBiosId { get; } + /// Gets or sets the target VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target VM display name.", + SerializedName = @"targetVmName", + PossibleTypes = new [] { typeof(string) })] + string TargetVMName { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target test network Id within AzStackHCI Cluster.", + SerializedName = @"testNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TestNetworkId { get; set; } + + } + /// HyperV to AzStackHCI Protected item model custom properties. + internal partial interface IHyperVToAzStackHciprotectedItemModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal + { + /// Gets or sets the location of the protected item. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Primary", "Recovery")] + string ActiveLocation { get; set; } + /// Gets or sets the location of Azure Arc HCI custom location resource. + string CustomLocationRegion { get; set; } + /// Gets or sets the list of disks to replicate. + System.Collections.Generic.List DisksToInclude { get; set; } + /// Protected item dynamic memory config. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get; set; } + /// Gets or sets maximum memory in MB. + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets the ARM Id of the discovered machine. + string FabricDiscoveryMachineId { get; set; } + /// Gets or sets the recovery point Id to which the VM was failed over. + string FailoverRecoveryPointId { get; set; } + /// Gets or sets the firmware type. + string FirmwareType { get; set; } + /// Gets or sets the hypervisor generation of the virtual machine. + string HyperVGeneration { get; set; } + /// + /// Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks + /// in the source VM. + /// + int? InitialReplicationProgressPercentage { get; set; } + /// Gets or sets a value indicating whether memory is dynamical. + bool? IsDynamicRam { get; set; } + /// Gets or sets the last recovery point Id. + string LastRecoveryPointId { get; set; } + /// Gets or sets the last recovery point received time. + global::System.DateTime? LastRecoveryPointReceived { get; set; } + /// Gets or sets the latest timestamp that replication status is updated. + global::System.DateTime? LastReplicationUpdateTime { get; set; } + /// Gets or sets the list of VM NIC to replicate. + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the name of the OS. + string OSName { get; set; } + /// Gets or sets the type of the OS. + string OSType { get; set; } + /// Gets or sets the list of protected disks. + System.Collections.Generic.List ProtectedDisk { get; set; } + /// Gets or sets the VM NIC details. + System.Collections.Generic.List ProtectedNic { get; set; } + /// + /// Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source + /// VM. + /// + int? ResyncProgressPercentage { get; set; } + /// Gets or sets the Run As account Id. + string RunAsAccountId { get; set; } + /// Gets or sets the source appliance name. + string SourceApplianceName { get; set; } + /// Gets or sets the source VM CPU cores. + int? SourceCpuCore { get; set; } + /// Gets or sets the source fabric agent name. + string SourceFabricAgentName { get; set; } + /// Gets or sets the source VM ram memory size in megabytes. + double? SourceMemoryInMegaByte { get; set; } + /// Gets or sets the source VM display name. + string SourceVMName { get; set; } + /// Gets or sets the target storage container ARM Id. + string StorageContainerId { get; set; } + /// Gets or sets the target appliance name. + string TargetApplianceName { get; set; } + /// Gets or sets the Target Arc Cluster Custom Location ARM Id. + string TargetArcClusterCustomLocationId { get; set; } + /// Gets or sets the Target AzStackHCI cluster name. + string TargetAzStackHciClusterName { get; set; } + /// Gets or sets the target CPU cores. + int? TargetCpuCore { get; set; } + /// Gets or sets the target fabric agent name. + string TargetFabricAgentName { get; set; } + /// Gets or sets the Target HCI Cluster ARM Id. + string TargetHciClusterId { get; set; } + /// Gets or sets the target location. + string TargetLocation { get; set; } + /// Gets or sets the target memory in mega-bytes. + int? TargetMemoryInMegaByte { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + string TargetNetworkId { get; set; } + /// Gets or sets the target resource group ARM Id. + string TargetResourceGroupId { get; set; } + /// Gets or sets the BIOS Id of the target AzStackHCI VM. + string TargetVMBiosId { get; set; } + /// Gets or sets the target VM display name. + string TargetVMName { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + string TestNetworkId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.json.cs new file mode 100644 index 00000000000..36397049c93 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI Protected item model custom properties. + public partial class HyperVToAzStackHciprotectedItemModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHciprotectedItemModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHciprotectedItemModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __protectedItemModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties(json); + {_dynamicMemoryConfig = If( json?.PropertyT("dynamicMemoryConfig"), out var __jsonDynamicMemoryConfig) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig.FromJson(__jsonDynamicMemoryConfig) : _dynamicMemoryConfig;} + {_activeLocation = If( json?.PropertyT("activeLocation"), out var __jsonActiveLocation) ? (string)__jsonActiveLocation : (string)_activeLocation;} + {_targetHciClusterId = If( json?.PropertyT("targetHciClusterId"), out var __jsonTargetHciClusterId) ? (string)__jsonTargetHciClusterId : (string)_targetHciClusterId;} + {_targetArcClusterCustomLocationId = If( json?.PropertyT("targetArcClusterCustomLocationId"), out var __jsonTargetArcClusterCustomLocationId) ? (string)__jsonTargetArcClusterCustomLocationId : (string)_targetArcClusterCustomLocationId;} + {_targetAzStackHciClusterName = If( json?.PropertyT("targetAzStackHciClusterName"), out var __jsonTargetAzStackHciClusterName) ? (string)__jsonTargetAzStackHciClusterName : (string)_targetAzStackHciClusterName;} + {_fabricDiscoveryMachineId = If( json?.PropertyT("fabricDiscoveryMachineId"), out var __jsonFabricDiscoveryMachineId) ? (string)__jsonFabricDiscoveryMachineId : (string)_fabricDiscoveryMachineId;} + {_disksToInclude = If( json?.PropertyT("disksToInclude"), out var __jsonDisksToInclude) ? If( __jsonDisksToInclude as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcidiskInput) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcidiskInput.FromJson(__u) )) ))() : null : _disksToInclude;} + {_nicsToInclude = If( json?.PropertyT("nicsToInclude"), out var __jsonNicsToInclude) ? If( __jsonNicsToInclude as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcinicInput.FromJson(__p) )) ))() : null : _nicsToInclude;} + {_sourceVMName = If( json?.PropertyT("sourceVmName"), out var __jsonSourceVMName) ? (string)__jsonSourceVMName : (string)_sourceVMName;} + {_sourceCpuCore = If( json?.PropertyT("sourceCpuCores"), out var __jsonSourceCpuCores) ? (int?)__jsonSourceCpuCores : _sourceCpuCore;} + {_sourceMemoryInMegaByte = If( json?.PropertyT("sourceMemoryInMegaBytes"), out var __jsonSourceMemoryInMegaBytes) ? (double?)__jsonSourceMemoryInMegaBytes : _sourceMemoryInMegaByte;} + {_targetVMName = If( json?.PropertyT("targetVmName"), out var __jsonTargetVMName) ? (string)__jsonTargetVMName : (string)_targetVMName;} + {_targetResourceGroupId = If( json?.PropertyT("targetResourceGroupId"), out var __jsonTargetResourceGroupId) ? (string)__jsonTargetResourceGroupId : (string)_targetResourceGroupId;} + {_storageContainerId = If( json?.PropertyT("storageContainerId"), out var __jsonStorageContainerId) ? (string)__jsonStorageContainerId : (string)_storageContainerId;} + {_hyperVGeneration = If( json?.PropertyT("hyperVGeneration"), out var __jsonHyperVGeneration) ? (string)__jsonHyperVGeneration : (string)_hyperVGeneration;} + {_targetNetworkId = If( json?.PropertyT("targetNetworkId"), out var __jsonTargetNetworkId) ? (string)__jsonTargetNetworkId : (string)_targetNetworkId;} + {_testNetworkId = If( json?.PropertyT("testNetworkId"), out var __jsonTestNetworkId) ? (string)__jsonTestNetworkId : (string)_testNetworkId;} + {_targetCpuCore = If( json?.PropertyT("targetCpuCores"), out var __jsonTargetCpuCores) ? (int?)__jsonTargetCpuCores : _targetCpuCore;} + {_isDynamicRam = If( json?.PropertyT("isDynamicRam"), out var __jsonIsDynamicRam) ? (bool?)__jsonIsDynamicRam : _isDynamicRam;} + {_targetMemoryInMegaByte = If( json?.PropertyT("targetMemoryInMegaBytes"), out var __jsonTargetMemoryInMegaBytes) ? (int?)__jsonTargetMemoryInMegaBytes : _targetMemoryInMegaByte;} + {_runAsAccountId = If( json?.PropertyT("runAsAccountId"), out var __jsonRunAsAccountId) ? (string)__jsonRunAsAccountId : (string)_runAsAccountId;} + {_sourceFabricAgentName = If( json?.PropertyT("sourceFabricAgentName"), out var __jsonSourceFabricAgentName) ? (string)__jsonSourceFabricAgentName : (string)_sourceFabricAgentName;} + {_targetFabricAgentName = If( json?.PropertyT("targetFabricAgentName"), out var __jsonTargetFabricAgentName) ? (string)__jsonTargetFabricAgentName : (string)_targetFabricAgentName;} + {_sourceApplianceName = If( json?.PropertyT("sourceApplianceName"), out var __jsonSourceApplianceName) ? (string)__jsonSourceApplianceName : (string)_sourceApplianceName;} + {_targetApplianceName = If( json?.PropertyT("targetApplianceName"), out var __jsonTargetApplianceName) ? (string)__jsonTargetApplianceName : (string)_targetApplianceName;} + {_oSType = If( json?.PropertyT("osType"), out var __jsonOSType) ? (string)__jsonOSType : (string)_oSType;} + {_oSName = If( json?.PropertyT("osName"), out var __jsonOSName) ? (string)__jsonOSName : (string)_oSName;} + {_firmwareType = If( json?.PropertyT("firmwareType"), out var __jsonFirmwareType) ? (string)__jsonFirmwareType : (string)_firmwareType;} + {_targetLocation = If( json?.PropertyT("targetLocation"), out var __jsonTargetLocation) ? (string)__jsonTargetLocation : (string)_targetLocation;} + {_customLocationRegion = If( json?.PropertyT("customLocationRegion"), out var __jsonCustomLocationRegion) ? (string)__jsonCustomLocationRegion : (string)_customLocationRegion;} + {_failoverRecoveryPointId = If( json?.PropertyT("failoverRecoveryPointId"), out var __jsonFailoverRecoveryPointId) ? (string)__jsonFailoverRecoveryPointId : (string)_failoverRecoveryPointId;} + {_lastRecoveryPointReceived = If( json?.PropertyT("lastRecoveryPointReceived"), out var __jsonLastRecoveryPointReceived) ? global::System.DateTime.TryParse((string)__jsonLastRecoveryPointReceived, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastRecoveryPointReceivedValue) ? __jsonLastRecoveryPointReceivedValue : _lastRecoveryPointReceived : _lastRecoveryPointReceived;} + {_lastRecoveryPointId = If( json?.PropertyT("lastRecoveryPointId"), out var __jsonLastRecoveryPointId) ? (string)__jsonLastRecoveryPointId : (string)_lastRecoveryPointId;} + {_initialReplicationProgressPercentage = If( json?.PropertyT("initialReplicationProgressPercentage"), out var __jsonInitialReplicationProgressPercentage) ? (int?)__jsonInitialReplicationProgressPercentage : _initialReplicationProgressPercentage;} + {_resyncProgressPercentage = If( json?.PropertyT("resyncProgressPercentage"), out var __jsonResyncProgressPercentage) ? (int?)__jsonResyncProgressPercentage : _resyncProgressPercentage;} + {_protectedDisk = If( json?.PropertyT("protectedDisks"), out var __jsonProtectedDisks) ? If( __jsonProtectedDisks as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedDiskProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHciprotectedDiskProperties.FromJson(__k) )) ))() : null : _protectedDisk;} + {_protectedNic = If( json?.PropertyT("protectedNics"), out var __jsonProtectedNics) ? If( __jsonProtectedNics as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __g) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__g, (__f)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHciprotectedNicProperties.FromJson(__f) )) ))() : null : _protectedNic;} + {_targetVMBiosId = If( json?.PropertyT("targetVmBiosId"), out var __jsonTargetVMBiosId) ? (string)__jsonTargetVMBiosId : (string)_targetVMBiosId;} + {_lastReplicationUpdateTime = If( json?.PropertyT("lastReplicationUpdateTime"), out var __jsonLastReplicationUpdateTime) ? global::System.DateTime.TryParse((string)__jsonLastReplicationUpdateTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastReplicationUpdateTimeValue) ? __jsonLastReplicationUpdateTimeValue : _lastReplicationUpdateTime : _lastReplicationUpdateTime;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __protectedItemModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != this._dynamicMemoryConfig ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._dynamicMemoryConfig.ToJson(null,serializationMode) : null, "dynamicMemoryConfig" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._activeLocation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._activeLocation.ToString()) : null, "activeLocation" ,container.Add ); + } + AddIf( null != (((object)this._targetHciClusterId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetHciClusterId.ToString()) : null, "targetHciClusterId" ,container.Add ); + AddIf( null != (((object)this._targetArcClusterCustomLocationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetArcClusterCustomLocationId.ToString()) : null, "targetArcClusterCustomLocationId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetAzStackHciClusterName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetAzStackHciClusterName.ToString()) : null, "targetAzStackHciClusterName" ,container.Add ); + } + AddIf( null != (((object)this._fabricDiscoveryMachineId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricDiscoveryMachineId.ToString()) : null, "fabricDiscoveryMachineId" ,container.Add ); + if (null != this._disksToInclude) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._disksToInclude ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("disksToInclude",__w); + } + if (null != this._nicsToInclude) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._nicsToInclude ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("nicsToInclude",__r); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceVMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceVMName.ToString()) : null, "sourceVmName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._sourceCpuCore ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._sourceCpuCore) : null, "sourceCpuCores" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._sourceMemoryInMegaByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((double)this._sourceMemoryInMegaByte) : null, "sourceMemoryInMegaBytes" ,container.Add ); + } + AddIf( null != (((object)this._targetVMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetVMName.ToString()) : null, "targetVmName" ,container.Add ); + AddIf( null != (((object)this._targetResourceGroupId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetResourceGroupId.ToString()) : null, "targetResourceGroupId" ,container.Add ); + AddIf( null != (((object)this._storageContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerId.ToString()) : null, "storageContainerId" ,container.Add ); + AddIf( null != (((object)this._hyperVGeneration)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._hyperVGeneration.ToString()) : null, "hyperVGeneration" ,container.Add ); + AddIf( null != (((object)this._targetNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetNetworkId.ToString()) : null, "targetNetworkId" ,container.Add ); + AddIf( null != (((object)this._testNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testNetworkId.ToString()) : null, "testNetworkId" ,container.Add ); + AddIf( null != this._targetCpuCore ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetCpuCore) : null, "targetCpuCores" ,container.Add ); + AddIf( null != this._isDynamicRam ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamicRam) : null, "isDynamicRam" ,container.Add ); + AddIf( null != this._targetMemoryInMegaByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetMemoryInMegaByte) : null, "targetMemoryInMegaBytes" ,container.Add ); + AddIf( null != (((object)this._runAsAccountId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._runAsAccountId.ToString()) : null, "runAsAccountId" ,container.Add ); + AddIf( null != (((object)this._sourceFabricAgentName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceFabricAgentName.ToString()) : null, "sourceFabricAgentName" ,container.Add ); + AddIf( null != (((object)this._targetFabricAgentName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetFabricAgentName.ToString()) : null, "targetFabricAgentName" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceApplianceName.ToString()) : null, "sourceApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetApplianceName.ToString()) : null, "targetApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._oSType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._oSType.ToString()) : null, "osType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._oSName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._oSName.ToString()) : null, "osName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._firmwareType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._firmwareType.ToString()) : null, "firmwareType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetLocation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetLocation.ToString()) : null, "targetLocation" ,container.Add ); + } + AddIf( null != (((object)this._customLocationRegion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._customLocationRegion.ToString()) : null, "customLocationRegion" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._failoverRecoveryPointId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._failoverRecoveryPointId.ToString()) : null, "failoverRecoveryPointId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastRecoveryPointReceived ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastRecoveryPointReceived?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastRecoveryPointReceived" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._lastRecoveryPointId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastRecoveryPointId.ToString()) : null, "lastRecoveryPointId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._initialReplicationProgressPercentage ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._initialReplicationProgressPercentage) : null, "initialReplicationProgressPercentage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resyncProgressPercentage ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._resyncProgressPercentage) : null, "resyncProgressPercentage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._protectedDisk) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __n in this._protectedDisk ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("protectedDisks",__m); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._protectedNic) + { + var __h = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __i in this._protectedNic ) + { + AddIf(__i?.ToJson(null, serializationMode) ,__h.Add); + } + container.Add("protectedNics",__h); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetVMBiosId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetVMBiosId.ToString()) : null, "targetVmBiosId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastReplicationUpdateTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastReplicationUpdateTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastReplicationUpdateTime" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.PowerShell.cs new file mode 100644 index 00000000000..461c2d747fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.PowerShell.cs @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateTypeConverter))] + public partial class HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the + /// content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__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 HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateTypeConverter))] + public partial interface IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.TypeConverter.cs new file mode 100644 index 00000000000..90a71963e40 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.cs new file mode 100644 index 00000000000..4e34cb6fe0a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI Protected item model custom properties. + public partial class HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate __protectedItemModelCustomPropertiesUpdate = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate(); + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig _dynamicMemoryConfig; + + /// Protected item dynamic memory config. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set => this._dynamicMemoryConfig = value; } + + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMaximumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMinimumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DynamicMemoryConfigTargetMemoryBufferPercentage { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage = value ?? default(int); } + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)__protectedItemModelCustomPropertiesUpdate).InstanceType = "HyperVToAzStackHCI"; } + + /// Backing field for property. + private bool? _isDynamicRam; + + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamicRam { get => this._isDynamicRam; set => this._isDynamicRam = value; } + + /// Internal Acessors for DynamicMemoryConfig + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal.DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set { {_dynamicMemoryConfig = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _nicsToInclude; + + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List NicsToInclude { get => this._nicsToInclude; set => this._nicsToInclude = value; } + + /// Backing field for property. + private string _oSType; + + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OSType { get => this._oSType; set => this._oSType = value; } + + /// Backing field for property. + private int? _targetCpuCore; + + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetCpuCore { get => this._targetCpuCore; set => this._targetCpuCore = value; } + + /// Backing field for property. + private int? _targetMemoryInMegaByte; + + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetMemoryInMegaByte { get => this._targetMemoryInMegaByte; set => this._targetMemoryInMegaByte = value; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate() + { + this.__protectedItemModelCustomPropertiesUpdate.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__protectedItemModelCustomPropertiesUpdate), __protectedItemModelCustomPropertiesUpdate); + await eventListener.AssertObjectIsValid(nameof(__protectedItemModelCustomPropertiesUpdate), __protectedItemModelCustomPropertiesUpdate); + } + } + /// HyperV to AzStackHCI Protected item model custom properties. + public partial interface IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate + { + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets maximum memory in MB.", + SerializedName = @"maximumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets minimum memory in MB.", + SerializedName = @"minimumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets target memory buffer in %.", + SerializedName = @"targetMemoryBufferPercentage", + PossibleTypes = new [] { typeof(int) })] + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether memory is dynamical.", + SerializedName = @"isDynamicRam", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamicRam { get; set; } + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of VM NIC to replicate.", + SerializedName = @"nicsToInclude", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput) })] + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of the OS.", + SerializedName = @"osType", + PossibleTypes = new [] { typeof(string) })] + string OSType { get; set; } + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target CPU cores.", + SerializedName = @"targetCpuCores", + PossibleTypes = new [] { typeof(int) })] + int? TargetCpuCore { get; set; } + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target memory in mega-bytes.", + SerializedName = @"targetMemoryInMegaBytes", + PossibleTypes = new [] { typeof(int) })] + int? TargetMemoryInMegaByte { get; set; } + + } + /// HyperV to AzStackHCI Protected item model custom properties. + internal partial interface IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal + { + /// Protected item dynamic memory config. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get; set; } + /// Gets or sets maximum memory in MB. + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets a value indicating whether memory is dynamical. + bool? IsDynamicRam { get; set; } + /// Gets or sets the list of VM NIC to replicate. + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the type of the OS. + string OSType { get; set; } + /// Gets or sets the target CPU cores. + int? TargetCpuCore { get; set; } + /// Gets or sets the target memory in mega-bytes. + int? TargetMemoryInMegaByte { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.json.cs new file mode 100644 index 00000000000..c01c37ac60c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI Protected item model custom properties. + public partial class HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __protectedItemModelCustomPropertiesUpdate = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate(json); + {_dynamicMemoryConfig = If( json?.PropertyT("dynamicMemoryConfig"), out var __jsonDynamicMemoryConfig) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig.FromJson(__jsonDynamicMemoryConfig) : _dynamicMemoryConfig;} + {_nicsToInclude = If( json?.PropertyT("nicsToInclude"), out var __jsonNicsToInclude) ? If( __jsonNicsToInclude as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcinicInput) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HyperVToAzStackHcinicInput.FromJson(__u) )) ))() : null : _nicsToInclude;} + {_targetCpuCore = If( json?.PropertyT("targetCpuCores"), out var __jsonTargetCpuCores) ? (int?)__jsonTargetCpuCores : _targetCpuCore;} + {_isDynamicRam = If( json?.PropertyT("isDynamicRam"), out var __jsonIsDynamicRam) ? (bool?)__jsonIsDynamicRam : _isDynamicRam;} + {_targetMemoryInMegaByte = If( json?.PropertyT("targetMemoryInMegaBytes"), out var __jsonTargetMemoryInMegaBytes) ? (int?)__jsonTargetMemoryInMegaBytes : _targetMemoryInMegaByte;} + {_oSType = If( json?.PropertyT("osType"), out var __jsonOSType) ? (string)__jsonOSType : (string)_oSType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __protectedItemModelCustomPropertiesUpdate?.ToJson(container, serializationMode); + AddIf( null != this._dynamicMemoryConfig ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._dynamicMemoryConfig.ToJson(null,serializationMode) : null, "dynamicMemoryConfig" ,container.Add ); + if (null != this._nicsToInclude) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._nicsToInclude ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("nicsToInclude",__w); + } + AddIf( null != this._targetCpuCore ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetCpuCore) : null, "targetCpuCores" ,container.Add ); + AddIf( null != this._isDynamicRam ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamicRam) : null, "isDynamicRam" ,container.Add ); + AddIf( null != this._targetMemoryInMegaByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetMemoryInMegaByte) : null, "targetMemoryInMegaBytes" ,container.Add ); + AddIf( null != (((object)this._oSType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._oSType.ToString()) : null, "osType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.PowerShell.cs new file mode 100644 index 00000000000..9c6d3eb352e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.PowerShell.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperVToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedNicPropertiesTypeConverter))] + public partial class HyperVToAzStackHciprotectedNicProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHciprotectedNicProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHciprotectedNicProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHciprotectedNicProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("MacAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).MacAddress = (string) content.GetValueForProperty("MacAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).MacAddress, global::System.Convert.ToString); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover, 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 HyperVToAzStackHciprotectedNicProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("MacAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).MacAddress = (string) content.GetValueForProperty("MacAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).MacAddress, global::System.Convert.ToString); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperVToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHciprotectedNicPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHciprotectedNicProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.TypeConverter.cs new file mode 100644 index 00000000000..2721ebe0527 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHciprotectedNicPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHciprotectedNicProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedNicProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHciprotectedNicProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.cs new file mode 100644 index 00000000000..1b3f818f337 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStackHCI NIC properties. + public partial class HyperVToAzStackHciprotectedNicProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal + { + + /// Backing field for property. + private string _macAddress; + + /// Gets or sets the NIC mac address. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MacAddress { get => this._macAddress; } + + /// Internal Acessors for MacAddress + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal.MacAddress { get => this._macAddress; set { {_macAddress = value;} } } + + /// Internal Acessors for NetworkName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal.NetworkName { get => this._networkName; set { {_networkName = value;} } } + + /// Internal Acessors for NicId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal.NicId { get => this._nicId; set { {_nicId = value;} } } + + /// Internal Acessors for SelectionTypeForFailover + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal.SelectionTypeForFailover { get => this._selectionTypeForFailover; set { {_selectionTypeForFailover = value;} } } + + /// Internal Acessors for TargetNetworkId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal.TargetNetworkId { get => this._targetNetworkId; set { {_targetNetworkId = value;} } } + + /// Internal Acessors for TestNetworkId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicPropertiesInternal.TestNetworkId { get => this._testNetworkId; set { {_testNetworkId = value;} } } + + /// Backing field for property. + private string _networkName; + + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NetworkName { get => this._networkName; } + + /// Backing field for property. + private string _nicId; + + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NicId { get => this._nicId; } + + /// Backing field for property. + private string _selectionTypeForFailover; + + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SelectionTypeForFailover { get => this._selectionTypeForFailover; } + + /// Backing field for property. + private string _targetNetworkId; + + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetNetworkId { get => this._targetNetworkId; } + + /// Backing field for property. + private string _testNetworkId; + + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestNetworkId { get => this._testNetworkId; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHciprotectedNicProperties() + { + + } + } + /// HyperVToAzStackHCI NIC properties. + public partial interface IHyperVToAzStackHciprotectedNicProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the NIC mac address. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the NIC mac address.", + SerializedName = @"macAddress", + PossibleTypes = new [] { typeof(string) })] + string MacAddress { get; } + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the network name.", + SerializedName = @"networkName", + PossibleTypes = new [] { typeof(string) })] + string NetworkName { get; } + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the NIC Id.", + SerializedName = @"nicId", + PossibleTypes = new [] { typeof(string) })] + string NicId { get; } + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the selection type of the NIC.", + SerializedName = @"selectionTypeForFailover", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target network Id within AzStackHCI Cluster.", + SerializedName = @"targetNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TargetNetworkId { get; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target test network Id within AzStackHCI Cluster.", + SerializedName = @"testNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TestNetworkId { get; } + + } + /// HyperVToAzStackHCI NIC properties. + internal partial interface IHyperVToAzStackHciprotectedNicPropertiesInternal + + { + /// Gets or sets the NIC mac address. + string MacAddress { get; set; } + /// Gets or sets the network name. + string NetworkName { get; set; } + /// Gets or sets the NIC Id. + string NicId { get; set; } + /// Gets or sets the selection type of the NIC. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + string TargetNetworkId { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + string TestNetworkId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.json.cs new file mode 100644 index 00000000000..cbe8ecc12de --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHciprotectedNicProperties.json.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperVToAzStackHCI NIC properties. + public partial class HyperVToAzStackHciprotectedNicProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHciprotectedNicProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHciprotectedNicProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHciprotectedNicProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nicId = If( json?.PropertyT("nicId"), out var __jsonNicId) ? (string)__jsonNicId : (string)_nicId;} + {_macAddress = If( json?.PropertyT("macAddress"), out var __jsonMacAddress) ? (string)__jsonMacAddress : (string)_macAddress;} + {_networkName = If( json?.PropertyT("networkName"), out var __jsonNetworkName) ? (string)__jsonNetworkName : (string)_networkName;} + {_targetNetworkId = If( json?.PropertyT("targetNetworkId"), out var __jsonTargetNetworkId) ? (string)__jsonTargetNetworkId : (string)_targetNetworkId;} + {_testNetworkId = If( json?.PropertyT("testNetworkId"), out var __jsonTestNetworkId) ? (string)__jsonTestNetworkId : (string)_testNetworkId;} + {_selectionTypeForFailover = If( json?.PropertyT("selectionTypeForFailover"), out var __jsonSelectionTypeForFailover) ? (string)__jsonSelectionTypeForFailover : (string)_selectionTypeForFailover;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._nicId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._nicId.ToString()) : null, "nicId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._macAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._macAddress.ToString()) : null, "macAddress" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._networkName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._networkName.ToString()) : null, "networkName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetNetworkId.ToString()) : null, "targetNetworkId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testNetworkId.ToString()) : null, "testNetworkId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._selectionTypeForFailover)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._selectionTypeForFailover.ToString()) : null, "selectionTypeForFailover" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..d60b89a3041 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV to AzStackHCI recovery point model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcirecoveryPointModelCustomPropertiesTypeConverter))] + public partial class HyperVToAzStackHcirecoveryPointModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHcirecoveryPointModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHcirecoveryPointModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHcirecoveryPointModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId = (System.Collections.Generic.List) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType, 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 HyperVToAzStackHcirecoveryPointModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId = (System.Collections.Generic.List) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV to AzStackHCI recovery point model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcirecoveryPointModelCustomPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHcirecoveryPointModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..905b0ff2ee3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHcirecoveryPointModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHcirecoveryPointModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHcirecoveryPointModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHcirecoveryPointModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.cs new file mode 100644 index 00000000000..be722dd845f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI recovery point model custom properties. + public partial class HyperVToAzStackHcirecoveryPointModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties __recoveryPointModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties(); + + /// Backing field for property. + private System.Collections.Generic.List _diskId; + + /// Gets or sets the list of the disk Ids. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List DiskId { get => this._diskId; } + + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)__recoveryPointModelCustomProperties).InstanceType = "HyperVToAzStackHCI"; } + + /// Internal Acessors for DiskId + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal.DiskId { get => this._diskId; set { {_diskId = value;} } } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHcirecoveryPointModelCustomProperties() + { + this.__recoveryPointModelCustomProperties.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__recoveryPointModelCustomProperties), __recoveryPointModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__recoveryPointModelCustomProperties), __recoveryPointModelCustomProperties); + } + } + /// HyperV to AzStackHCI recovery point model custom properties. + public partial interface IHyperVToAzStackHcirecoveryPointModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties + { + /// Gets or sets the list of the disk Ids. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of the disk Ids.", + SerializedName = @"diskIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List DiskId { get; } + + } + /// HyperV to AzStackHCI recovery point model custom properties. + internal partial interface IHyperVToAzStackHcirecoveryPointModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal + { + /// Gets or sets the list of the disk Ids. + System.Collections.Generic.List DiskId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.json.cs new file mode 100644 index 00000000000..5200fbf8f62 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcirecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI recovery point model custom properties. + public partial class HyperVToAzStackHcirecoveryPointModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcirecoveryPointModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHcirecoveryPointModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHcirecoveryPointModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __recoveryPointModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties(json); + {_diskId = If( json?.PropertyT("diskIds"), out var __jsonDiskIds) ? If( __jsonDiskIds as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _diskId;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __recoveryPointModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._diskId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._diskId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("diskIds",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..b50d48474b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.PowerShell.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// HyperV to AzStackHCI Replication extension model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcireplicationExtensionModelCustomPropertiesTypeConverter))] + public partial class HyperVToAzStackHcireplicationExtensionModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HyperVToAzStackHcireplicationExtensionModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HyperVToAzStackHcireplicationExtensionModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the + /// content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HyperVToAzStackHcireplicationExtensionModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("HyperVFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVFabricArmId = (string) content.GetValueForProperty("HyperVFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("HyperVSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVSiteId = (string) content.GetValueForProperty("HyperVSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVSiteId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId = (string) content.GetValueForProperty("AzStackHciFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId = (string) content.GetValueForProperty("AzStackHciSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId = (string) content.GetValueForProperty("StorageAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountSasSecretName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName = (string) content.GetValueForProperty("StorageAccountSasSecretName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName, global::System.Convert.ToString); + } + if (content.Contains("AsrServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri = (string) content.GetValueForProperty("AsrServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri, global::System.Convert.ToString); + } + if (content.Contains("RcmServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri = (string) content.GetValueForProperty("RcmServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri, global::System.Convert.ToString); + } + if (content.Contains("GatewayServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri = (string) content.GetValueForProperty("GatewayServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri, global::System.Convert.ToString); + } + if (content.Contains("SourceGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId = (string) content.GetValueForProperty("SourceGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("TargetGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId = (string) content.GetValueForProperty("TargetGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("SourceStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName = (string) content.GetValueForProperty("SourceStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("TargetStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName = (string) content.GetValueForProperty("TargetStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("ResourceLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation = (string) content.GetValueForProperty("ResourceLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup = (string) content.GetValueForProperty("ResourceGroup",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType, 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 HyperVToAzStackHcireplicationExtensionModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("HyperVFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVFabricArmId = (string) content.GetValueForProperty("HyperVFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("HyperVSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVSiteId = (string) content.GetValueForProperty("HyperVSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).HyperVSiteId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId = (string) content.GetValueForProperty("AzStackHciFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId = (string) content.GetValueForProperty("AzStackHciSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId = (string) content.GetValueForProperty("StorageAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountSasSecretName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName = (string) content.GetValueForProperty("StorageAccountSasSecretName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName, global::System.Convert.ToString); + } + if (content.Contains("AsrServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri = (string) content.GetValueForProperty("AsrServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri, global::System.Convert.ToString); + } + if (content.Contains("RcmServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri = (string) content.GetValueForProperty("RcmServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri, global::System.Convert.ToString); + } + if (content.Contains("GatewayServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri = (string) content.GetValueForProperty("GatewayServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri, global::System.Convert.ToString); + } + if (content.Contains("SourceGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId = (string) content.GetValueForProperty("SourceGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("TargetGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId = (string) content.GetValueForProperty("TargetGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("SourceStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName = (string) content.GetValueForProperty("SourceStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("TargetStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName = (string) content.GetValueForProperty("TargetStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("ResourceLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation = (string) content.GetValueForProperty("ResourceLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup = (string) content.GetValueForProperty("ResourceGroup",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// HyperV to AzStackHCI Replication extension model custom properties. + [System.ComponentModel.TypeConverter(typeof(HyperVToAzStackHcireplicationExtensionModelCustomPropertiesTypeConverter))] + public partial interface IHyperVToAzStackHcireplicationExtensionModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..560b40921a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HyperVToAzStackHcireplicationExtensionModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is + /// 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.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HyperVToAzStackHcireplicationExtensionModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HyperVToAzStackHcireplicationExtensionModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HyperVToAzStackHcireplicationExtensionModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.cs new file mode 100644 index 00000000000..e7764dbdb9c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.cs @@ -0,0 +1,414 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI Replication extension model custom properties. + public partial class HyperVToAzStackHcireplicationExtensionModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties __replicationExtensionModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties(); + + /// Backing field for property. + private string _asrServiceUri; + + /// Gets or sets the Uri of ASR. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AsrServiceUri { get => this._asrServiceUri; } + + /// Backing field for property. + private string _azStackHciFabricArmId; + + /// Gets or sets the ARM Id of the target AzStackHCI fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AzStackHciFabricArmId { get => this._azStackHciFabricArmId; set => this._azStackHciFabricArmId = value; } + + /// Backing field for property. + private string _azStackHciSiteId; + + /// Gets or sets the ARM Id of the AzStackHCI site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AzStackHciSiteId { get => this._azStackHciSiteId; } + + /// Backing field for property. + private string _gatewayServiceUri; + + /// Gets or sets the Uri of Gateway. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string GatewayServiceUri { get => this._gatewayServiceUri; } + + /// Backing field for property. + private string _hyperVFabricArmId; + + /// Gets or sets the ARM Id of the source HyperV fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HyperVFabricArmId { get => this._hyperVFabricArmId; set => this._hyperVFabricArmId = value; } + + /// Backing field for property. + private string _hyperVSiteId; + + /// Gets or sets the ARM Id of the HyperV site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HyperVSiteId { get => this._hyperVSiteId; } + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "HyperVToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)__replicationExtensionModelCustomProperties).InstanceType = "HyperVToAzStackHCI"; } + + /// Internal Acessors for AsrServiceUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.AsrServiceUri { get => this._asrServiceUri; set { {_asrServiceUri = value;} } } + + /// Internal Acessors for AzStackHciSiteId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.AzStackHciSiteId { get => this._azStackHciSiteId; set { {_azStackHciSiteId = value;} } } + + /// Internal Acessors for GatewayServiceUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.GatewayServiceUri { get => this._gatewayServiceUri; set { {_gatewayServiceUri = value;} } } + + /// Internal Acessors for HyperVSiteId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.HyperVSiteId { get => this._hyperVSiteId; set { {_hyperVSiteId = value;} } } + + /// Internal Acessors for RcmServiceUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.RcmServiceUri { get => this._rcmServiceUri; set { {_rcmServiceUri = value;} } } + + /// Internal Acessors for ResourceGroup + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.ResourceGroup { get => this._resourceGroup; set { {_resourceGroup = value;} } } + + /// Internal Acessors for ResourceLocation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.ResourceLocation { get => this._resourceLocation; set { {_resourceLocation = value;} } } + + /// Internal Acessors for SourceGatewayServiceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.SourceGatewayServiceId { get => this._sourceGatewayServiceId; set { {_sourceGatewayServiceId = value;} } } + + /// Internal Acessors for SourceStorageContainerName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.SourceStorageContainerName { get => this._sourceStorageContainerName; set { {_sourceStorageContainerName = value;} } } + + /// Internal Acessors for SubscriptionId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.SubscriptionId { get => this._subscriptionId; set { {_subscriptionId = value;} } } + + /// Internal Acessors for TargetGatewayServiceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.TargetGatewayServiceId { get => this._targetGatewayServiceId; set { {_targetGatewayServiceId = value;} } } + + /// Internal Acessors for TargetStorageContainerName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal.TargetStorageContainerName { get => this._targetStorageContainerName; set { {_targetStorageContainerName = value;} } } + + /// Backing field for property. + private string _rcmServiceUri; + + /// Gets or sets the Uri of Rcm. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RcmServiceUri { get => this._rcmServiceUri; } + + /// Backing field for property. + private string _resourceGroup; + + /// Gets or sets the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroup { get => this._resourceGroup; } + + /// Backing field for property. + private string _resourceLocation; + + /// Gets or sets the resource location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceLocation { get => this._resourceLocation; } + + /// Backing field for property. + private string _sourceGatewayServiceId; + + /// Gets or sets the gateway service Id of source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceGatewayServiceId { get => this._sourceGatewayServiceId; } + + /// Backing field for property. + private string _sourceStorageContainerName; + + /// Gets or sets the source storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceStorageContainerName { get => this._sourceStorageContainerName; } + + /// Backing field for property. + private string _storageAccountId; + + /// Gets or sets the storage account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageAccountId { get => this._storageAccountId; set => this._storageAccountId = value; } + + /// Backing field for property. + private string _storageAccountSasSecretName; + + /// Gets or sets the Sas Secret of storage account. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageAccountSasSecretName { get => this._storageAccountSasSecretName; set => this._storageAccountSasSecretName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// Gets or sets the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; } + + /// Backing field for property. + private string _targetGatewayServiceId; + + /// Gets or sets the gateway service Id of target. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetGatewayServiceId { get => this._targetGatewayServiceId; } + + /// Backing field for property. + private string _targetStorageContainerName; + + /// Gets or sets the target storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetStorageContainerName { get => this._targetStorageContainerName; } + + /// + /// Creates an new instance. + /// + public HyperVToAzStackHcireplicationExtensionModelCustomProperties() + { + this.__replicationExtensionModelCustomProperties.InstanceType = "HyperVToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__replicationExtensionModelCustomProperties), __replicationExtensionModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__replicationExtensionModelCustomProperties), __replicationExtensionModelCustomProperties); + } + } + /// HyperV to AzStackHCI Replication extension model custom properties. + public partial interface IHyperVToAzStackHcireplicationExtensionModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties + { + /// Gets or sets the Uri of ASR. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Uri of ASR.", + SerializedName = @"asrServiceUri", + PossibleTypes = new [] { typeof(string) })] + string AsrServiceUri { get; } + /// Gets or sets the ARM Id of the target AzStackHCI fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the target AzStackHCI fabric.", + SerializedName = @"azStackHciFabricArmId", + PossibleTypes = new [] { typeof(string) })] + string AzStackHciFabricArmId { get; set; } + /// Gets or sets the ARM Id of the AzStackHCI site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the ARM Id of the AzStackHCI site.", + SerializedName = @"azStackHciSiteId", + PossibleTypes = new [] { typeof(string) })] + string AzStackHciSiteId { get; } + /// Gets or sets the Uri of Gateway. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Uri of Gateway.", + SerializedName = @"gatewayServiceUri", + PossibleTypes = new [] { typeof(string) })] + string GatewayServiceUri { get; } + /// Gets or sets the ARM Id of the source HyperV fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the source HyperV fabric.", + SerializedName = @"hyperVFabricArmId", + PossibleTypes = new [] { typeof(string) })] + string HyperVFabricArmId { get; set; } + /// Gets or sets the ARM Id of the HyperV site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the ARM Id of the HyperV site.", + SerializedName = @"hyperVSiteId", + PossibleTypes = new [] { typeof(string) })] + string HyperVSiteId { get; } + /// Gets or sets the Uri of Rcm. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Uri of Rcm.", + SerializedName = @"rcmServiceUri", + PossibleTypes = new [] { typeof(string) })] + string RcmServiceUri { get; } + /// Gets or sets the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource group.", + SerializedName = @"resourceGroup", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroup { get; } + /// Gets or sets the resource location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource location.", + SerializedName = @"resourceLocation", + PossibleTypes = new [] { typeof(string) })] + string ResourceLocation { get; } + /// Gets or sets the gateway service Id of source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the gateway service Id of source.", + SerializedName = @"sourceGatewayServiceId", + PossibleTypes = new [] { typeof(string) })] + string SourceGatewayServiceId { get; } + /// Gets or sets the source storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source storage container name.", + SerializedName = @"sourceStorageContainerName", + PossibleTypes = new [] { typeof(string) })] + string SourceStorageContainerName { get; } + /// Gets or sets the storage account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the storage account Id.", + SerializedName = @"storageAccountId", + PossibleTypes = new [] { typeof(string) })] + string StorageAccountId { get; set; } + /// Gets or sets the Sas Secret of storage account. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Sas Secret of storage account.", + SerializedName = @"storageAccountSasSecretName", + PossibleTypes = new [] { typeof(string) })] + string StorageAccountSasSecretName { get; set; } + /// Gets or sets the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; } + /// Gets or sets the gateway service Id of target. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the gateway service Id of target.", + SerializedName = @"targetGatewayServiceId", + PossibleTypes = new [] { typeof(string) })] + string TargetGatewayServiceId { get; } + /// Gets or sets the target storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target storage container name.", + SerializedName = @"targetStorageContainerName", + PossibleTypes = new [] { typeof(string) })] + string TargetStorageContainerName { get; } + + } + /// HyperV to AzStackHCI Replication extension model custom properties. + internal partial interface IHyperVToAzStackHcireplicationExtensionModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal + { + /// Gets or sets the Uri of ASR. + string AsrServiceUri { get; set; } + /// Gets or sets the ARM Id of the target AzStackHCI fabric. + string AzStackHciFabricArmId { get; set; } + /// Gets or sets the ARM Id of the AzStackHCI site. + string AzStackHciSiteId { get; set; } + /// Gets or sets the Uri of Gateway. + string GatewayServiceUri { get; set; } + /// Gets or sets the ARM Id of the source HyperV fabric. + string HyperVFabricArmId { get; set; } + /// Gets or sets the ARM Id of the HyperV site. + string HyperVSiteId { get; set; } + /// Gets or sets the Uri of Rcm. + string RcmServiceUri { get; set; } + /// Gets or sets the resource group. + string ResourceGroup { get; set; } + /// Gets or sets the resource location. + string ResourceLocation { get; set; } + /// Gets or sets the gateway service Id of source. + string SourceGatewayServiceId { get; set; } + /// Gets or sets the source storage container name. + string SourceStorageContainerName { get; set; } + /// Gets or sets the storage account Id. + string StorageAccountId { get; set; } + /// Gets or sets the Sas Secret of storage account. + string StorageAccountSasSecretName { get; set; } + /// Gets or sets the subscription. + string SubscriptionId { get; set; } + /// Gets or sets the gateway service Id of target. + string TargetGatewayServiceId { get; set; } + /// Gets or sets the target storage container name. + string TargetStorageContainerName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.json.cs new file mode 100644 index 00000000000..1e99de3fe66 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/HyperVToAzStackHcireplicationExtensionModelCustomProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// HyperV to AzStackHCI Replication extension model custom properties. + public partial class HyperVToAzStackHcireplicationExtensionModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHyperVToAzStackHcireplicationExtensionModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new HyperVToAzStackHcireplicationExtensionModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal HyperVToAzStackHcireplicationExtensionModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __replicationExtensionModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties(json); + {_hyperVFabricArmId = If( json?.PropertyT("hyperVFabricArmId"), out var __jsonHyperVFabricArmId) ? (string)__jsonHyperVFabricArmId : (string)_hyperVFabricArmId;} + {_hyperVSiteId = If( json?.PropertyT("hyperVSiteId"), out var __jsonHyperVSiteId) ? (string)__jsonHyperVSiteId : (string)_hyperVSiteId;} + {_azStackHciFabricArmId = If( json?.PropertyT("azStackHciFabricArmId"), out var __jsonAzStackHciFabricArmId) ? (string)__jsonAzStackHciFabricArmId : (string)_azStackHciFabricArmId;} + {_azStackHciSiteId = If( json?.PropertyT("azStackHciSiteId"), out var __jsonAzStackHciSiteId) ? (string)__jsonAzStackHciSiteId : (string)_azStackHciSiteId;} + {_storageAccountId = If( json?.PropertyT("storageAccountId"), out var __jsonStorageAccountId) ? (string)__jsonStorageAccountId : (string)_storageAccountId;} + {_storageAccountSasSecretName = If( json?.PropertyT("storageAccountSasSecretName"), out var __jsonStorageAccountSasSecretName) ? (string)__jsonStorageAccountSasSecretName : (string)_storageAccountSasSecretName;} + {_asrServiceUri = If( json?.PropertyT("asrServiceUri"), out var __jsonAsrServiceUri) ? (string)__jsonAsrServiceUri : (string)_asrServiceUri;} + {_rcmServiceUri = If( json?.PropertyT("rcmServiceUri"), out var __jsonRcmServiceUri) ? (string)__jsonRcmServiceUri : (string)_rcmServiceUri;} + {_gatewayServiceUri = If( json?.PropertyT("gatewayServiceUri"), out var __jsonGatewayServiceUri) ? (string)__jsonGatewayServiceUri : (string)_gatewayServiceUri;} + {_sourceGatewayServiceId = If( json?.PropertyT("sourceGatewayServiceId"), out var __jsonSourceGatewayServiceId) ? (string)__jsonSourceGatewayServiceId : (string)_sourceGatewayServiceId;} + {_targetGatewayServiceId = If( json?.PropertyT("targetGatewayServiceId"), out var __jsonTargetGatewayServiceId) ? (string)__jsonTargetGatewayServiceId : (string)_targetGatewayServiceId;} + {_sourceStorageContainerName = If( json?.PropertyT("sourceStorageContainerName"), out var __jsonSourceStorageContainerName) ? (string)__jsonSourceStorageContainerName : (string)_sourceStorageContainerName;} + {_targetStorageContainerName = If( json?.PropertyT("targetStorageContainerName"), out var __jsonTargetStorageContainerName) ? (string)__jsonTargetStorageContainerName : (string)_targetStorageContainerName;} + {_resourceLocation = If( json?.PropertyT("resourceLocation"), out var __jsonResourceLocation) ? (string)__jsonResourceLocation : (string)_resourceLocation;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_resourceGroup = If( json?.PropertyT("resourceGroup"), out var __jsonResourceGroup) ? (string)__jsonResourceGroup : (string)_resourceGroup;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __replicationExtensionModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != (((object)this._hyperVFabricArmId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._hyperVFabricArmId.ToString()) : null, "hyperVFabricArmId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._hyperVSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._hyperVSiteId.ToString()) : null, "hyperVSiteId" ,container.Add ); + } + AddIf( null != (((object)this._azStackHciFabricArmId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._azStackHciFabricArmId.ToString()) : null, "azStackHciFabricArmId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._azStackHciSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._azStackHciSiteId.ToString()) : null, "azStackHciSiteId" ,container.Add ); + } + AddIf( null != (((object)this._storageAccountId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageAccountId.ToString()) : null, "storageAccountId" ,container.Add ); + AddIf( null != (((object)this._storageAccountSasSecretName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageAccountSasSecretName.ToString()) : null, "storageAccountSasSecretName" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._asrServiceUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._asrServiceUri.ToString()) : null, "asrServiceUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._rcmServiceUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._rcmServiceUri.ToString()) : null, "rcmServiceUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._gatewayServiceUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._gatewayServiceUri.ToString()) : null, "gatewayServiceUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceGatewayServiceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceGatewayServiceId.ToString()) : null, "sourceGatewayServiceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetGatewayServiceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetGatewayServiceId.ToString()) : null, "targetGatewayServiceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceStorageContainerName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceStorageContainerName.ToString()) : null, "sourceStorageContainerName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetStorageContainerName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetStorageContainerName.ToString()) : null, "targetStorageContainerName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceLocation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceLocation.ToString()) : null, "resourceLocation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceGroup)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceGroup.ToString()) : null, "resourceGroup" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.PowerShell.cs new file mode 100644 index 00000000000..9192d5cf876 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Identity model. + [System.ComponentModel.TypeConverter(typeof(IdentityModelTypeConverter))] + public partial class IdentityModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IIdentityModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IdentityModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IdentityModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IdentityModel(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("ApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ApplicationId, global::System.Convert.ToString); + } + if (content.Contains("ObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ObjectId, global::System.Convert.ToString); + } + if (content.Contains("Audience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).Audience = (string) content.GetValueForProperty("Audience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).Audience, global::System.Convert.ToString); + } + if (content.Contains("AadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).AadAuthority = (string) content.GetValueForProperty("AadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).AadAuthority, 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 IdentityModel(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("ApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ApplicationId, global::System.Convert.ToString); + } + if (content.Contains("ObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).ObjectId, global::System.Convert.ToString); + } + if (content.Contains("Audience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).Audience = (string) content.GetValueForProperty("Audience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).Audience, global::System.Convert.ToString); + } + if (content.Contains("AadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).AadAuthority = (string) content.GetValueForProperty("AadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)this).AadAuthority, 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.RecoveryServicesDataReplication.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(); + } + } + /// Identity model. + [System.ComponentModel.TypeConverter(typeof(IdentityModelTypeConverter))] + public partial interface IIdentityModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.TypeConverter.cs new file mode 100644 index 00000000000..5e210bf520a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IdentityModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IIdentityModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IdentityModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IdentityModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IdentityModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.cs new file mode 100644 index 00000000000..db1a77f62a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Identity model. + public partial class IdentityModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal + { + + /// Backing field for property. + private string _aadAuthority; + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AadAuthority { get => this._aadAuthority; set => this._aadAuthority = value; } + + /// Backing field for property. + private string _applicationId; + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ApplicationId { get => this._applicationId; set => this._applicationId = value; } + + /// Backing field for property. + private string _audience; + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Audience { get => this._audience; set => this._audience = value; } + + /// Backing field for property. + private string _objectId; + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ObjectId { get => this._objectId; set => this._objectId = value; } + + /// Backing field for property. + private string _tenantId; + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; set => this._tenantId = value; } + + /// Creates an new instance. + public IdentityModel() + { + + } + } + /// Identity model. + public partial interface IIdentityModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + string AadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + string Audience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string ObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + + } + /// Identity model. + internal partial interface IIdentityModelInternal + + { + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + string AadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + string ApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + string Audience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + string ObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.json.cs new file mode 100644 index 00000000000..12a05c0a676 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/IdentityModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Identity model. + public partial class IdentityModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new IdentityModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal IdentityModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)_tenantId;} + {_applicationId = If( json?.PropertyT("applicationId"), out var __jsonApplicationId) ? (string)__jsonApplicationId : (string)_applicationId;} + {_objectId = If( json?.PropertyT("objectId"), out var __jsonObjectId) ? (string)__jsonObjectId : (string)_objectId;} + {_audience = If( json?.PropertyT("audience"), out var __jsonAudience) ? (string)__jsonAudience : (string)_audience;} + {_aadAuthority = If( json?.PropertyT("aadAuthority"), out var __jsonAadAuthority) ? (string)__jsonAadAuthority : (string)_aadAuthority;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + AddIf( null != (((object)this._applicationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._applicationId.ToString()) : null, "applicationId" ,container.Add ); + AddIf( null != (((object)this._objectId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._objectId.ToString()) : null, "objectId" ,container.Add ); + AddIf( null != (((object)this._audience)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._audience.ToString()) : null, "audience" ,container.Add ); + AddIf( null != (((object)this._aadAuthority)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._aadAuthority.ToString()) : null, "aadAuthority" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.PowerShell.cs new file mode 100644 index 00000000000..9e8c006d784 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.PowerShell.cs @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Inner health error model. + [System.ComponentModel.TypeConverter(typeof(InnerHealthErrorModelTypeConverter))] + public partial class InnerHealthErrorModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new InnerHealthErrorModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new InnerHealthErrorModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal InnerHealthErrorModel(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.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("HealthCategory")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).HealthCategory = (string) content.GetValueForProperty("HealthCategory",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).HealthCategory, global::System.Convert.ToString); + } + if (content.Contains("Category")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Category = (string) content.GetValueForProperty("Category",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Category, global::System.Convert.ToString); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Source")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Source = (string) content.GetValueForProperty("Source",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Source, global::System.Convert.ToString); + } + if (content.Contains("CreationTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).CreationTime = (global::System.DateTime?) content.GetValueForProperty("CreationTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).CreationTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("IsCustomerResolvable")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).IsCustomerResolvable = (bool?) content.GetValueForProperty("IsCustomerResolvable",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).IsCustomerResolvable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Summary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Summary = (string) content.GetValueForProperty("Summary",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Summary, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Caus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Caus = (string) content.GetValueForProperty("Caus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Caus, global::System.Convert.ToString); + } + if (content.Contains("Recommendation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Recommendation = (string) content.GetValueForProperty("Recommendation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Recommendation, 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 InnerHealthErrorModel(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.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("HealthCategory")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).HealthCategory = (string) content.GetValueForProperty("HealthCategory",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).HealthCategory, global::System.Convert.ToString); + } + if (content.Contains("Category")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Category = (string) content.GetValueForProperty("Category",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Category, global::System.Convert.ToString); + } + if (content.Contains("Severity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Severity = (string) content.GetValueForProperty("Severity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Severity, global::System.Convert.ToString); + } + if (content.Contains("Source")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Source = (string) content.GetValueForProperty("Source",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Source, global::System.Convert.ToString); + } + if (content.Contains("CreationTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).CreationTime = (global::System.DateTime?) content.GetValueForProperty("CreationTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).CreationTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("IsCustomerResolvable")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).IsCustomerResolvable = (bool?) content.GetValueForProperty("IsCustomerResolvable",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).IsCustomerResolvable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Summary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Summary = (string) content.GetValueForProperty("Summary",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Summary, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Caus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Caus = (string) content.GetValueForProperty("Caus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Caus, global::System.Convert.ToString); + } + if (content.Contains("Recommendation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Recommendation = (string) content.GetValueForProperty("Recommendation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal)this).Recommendation, 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.RecoveryServicesDataReplication.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(); + } + } + /// Inner health error model. + [System.ComponentModel.TypeConverter(typeof(InnerHealthErrorModelTypeConverter))] + public partial interface IInnerHealthErrorModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.TypeConverter.cs new file mode 100644 index 00000000000..9ac7f369060 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class InnerHealthErrorModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return InnerHealthErrorModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return InnerHealthErrorModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return InnerHealthErrorModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.cs new file mode 100644 index 00000000000..f8681ffc4ac --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.cs @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Inner health error model. + public partial class InnerHealthErrorModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal + { + + /// Backing field for property. + private string _category; + + /// Gets or sets the error category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Category { get => this._category; } + + /// Backing field for property. + private string _caus; + + /// Gets or sets possible causes of the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Caus { get => this._caus; } + + /// Backing field for property. + private string _code; + + /// Gets or sets the error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private global::System.DateTime? _creationTime; + + /// Gets or sets the error creation time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? CreationTime { get => this._creationTime; } + + /// Backing field for property. + private string _healthCategory; + + /// Gets or sets the health category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HealthCategory { get => this._healthCategory; } + + /// Backing field for property. + private bool? _isCustomerResolvable; + + /// Gets or sets a value indicating whether the error is customer resolvable. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsCustomerResolvable { get => this._isCustomerResolvable; } + + /// Backing field for property. + private string _message; + + /// Gets or sets the error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Category + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Category { get => this._category; set { {_category = value;} } } + + /// Internal Acessors for Caus + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Caus { get => this._caus; set { {_caus = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for CreationTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.CreationTime { get => this._creationTime; set { {_creationTime = value;} } } + + /// Internal Acessors for HealthCategory + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.HealthCategory { get => this._healthCategory; set { {_healthCategory = value;} } } + + /// Internal Acessors for IsCustomerResolvable + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.IsCustomerResolvable { get => this._isCustomerResolvable; set { {_isCustomerResolvable = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Recommendation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Recommendation { get => this._recommendation; set { {_recommendation = value;} } } + + /// Internal Acessors for Severity + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Severity { get => this._severity; set { {_severity = value;} } } + + /// Internal Acessors for Source + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Source { get => this._source; set { {_source = value;} } } + + /// Internal Acessors for Summary + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModelInternal.Summary { get => this._summary; set { {_summary = value;} } } + + /// Backing field for property. + private string _recommendation; + + /// Gets or sets recommended action to resolve the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Recommendation { get => this._recommendation; } + + /// Backing field for property. + private string _severity; + + /// Gets or sets the error severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Severity { get => this._severity; } + + /// Backing field for property. + private string _source; + + /// Gets or sets the error source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Source { get => this._source; } + + /// Backing field for property. + private string _summary; + + /// Gets or sets the error summary. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Summary { get => this._summary; } + + /// Creates an new instance. + public InnerHealthErrorModel() + { + + } + } + /// Inner health error model. + public partial interface IInnerHealthErrorModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the error category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error category.", + SerializedName = @"category", + PossibleTypes = new [] { typeof(string) })] + string Category { get; } + /// Gets or sets possible causes of the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets possible causes of the error.", + SerializedName = @"causes", + PossibleTypes = new [] { typeof(string) })] + string Caus { get; } + /// Gets or sets the error code. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Gets or sets the error creation time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error creation time.", + SerializedName = @"creationTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreationTime { get; } + /// Gets or sets the health category. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the health category.", + SerializedName = @"healthCategory", + PossibleTypes = new [] { typeof(string) })] + string HealthCategory { get; } + /// Gets or sets a value indicating whether the error is customer resolvable. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether the error is customer resolvable.", + SerializedName = @"isCustomerResolvable", + PossibleTypes = new [] { typeof(bool) })] + bool? IsCustomerResolvable { get; } + /// Gets or sets the error message. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// Gets or sets recommended action to resolve the error. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets recommended action to resolve the error.", + SerializedName = @"recommendation", + PossibleTypes = new [] { typeof(string) })] + string Recommendation { get; } + /// Gets or sets the error severity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error severity.", + SerializedName = @"severity", + PossibleTypes = new [] { typeof(string) })] + string Severity { get; } + /// Gets or sets the error source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error source.", + SerializedName = @"source", + PossibleTypes = new [] { typeof(string) })] + string Source { get; } + /// Gets or sets the error summary. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the error summary.", + SerializedName = @"summary", + PossibleTypes = new [] { typeof(string) })] + string Summary { get; } + + } + /// Inner health error model. + internal partial interface IInnerHealthErrorModelInternal + + { + /// Gets or sets the error category. + string Category { get; set; } + /// Gets or sets possible causes of the error. + string Caus { get; set; } + /// Gets or sets the error code. + string Code { get; set; } + /// Gets or sets the error creation time. + global::System.DateTime? CreationTime { get; set; } + /// Gets or sets the health category. + string HealthCategory { get; set; } + /// Gets or sets a value indicating whether the error is customer resolvable. + bool? IsCustomerResolvable { get; set; } + /// Gets or sets the error message. + string Message { get; set; } + /// Gets or sets recommended action to resolve the error. + string Recommendation { get; set; } + /// Gets or sets the error severity. + string Severity { get; set; } + /// Gets or sets the error source. + string Source { get; set; } + /// Gets or sets the error summary. + string Summary { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.json.cs new file mode 100644 index 00000000000..c38a46d3389 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/InnerHealthErrorModel.json.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Inner health error model. + public partial class InnerHealthErrorModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IInnerHealthErrorModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new InnerHealthErrorModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal InnerHealthErrorModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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;} + {_healthCategory = If( json?.PropertyT("healthCategory"), out var __jsonHealthCategory) ? (string)__jsonHealthCategory : (string)_healthCategory;} + {_category = If( json?.PropertyT("category"), out var __jsonCategory) ? (string)__jsonCategory : (string)_category;} + {_severity = If( json?.PropertyT("severity"), out var __jsonSeverity) ? (string)__jsonSeverity : (string)_severity;} + {_source = If( json?.PropertyT("source"), out var __jsonSource) ? (string)__jsonSource : (string)_source;} + {_creationTime = If( json?.PropertyT("creationTime"), out var __jsonCreationTime) ? global::System.DateTime.TryParse((string)__jsonCreationTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreationTimeValue) ? __jsonCreationTimeValue : _creationTime : _creationTime;} + {_isCustomerResolvable = If( json?.PropertyT("isCustomerResolvable"), out var __jsonIsCustomerResolvable) ? (bool?)__jsonIsCustomerResolvable : _isCustomerResolvable;} + {_summary = If( json?.PropertyT("summary"), out var __jsonSummary) ? (string)__jsonSummary : (string)_summary;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)_message;} + {_caus = If( json?.PropertyT("causes"), out var __jsonCauses) ? (string)__jsonCauses : (string)_caus;} + {_recommendation = If( json?.PropertyT("recommendation"), out var __jsonRecommendation) ? (string)__jsonRecommendation : (string)_recommendation;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._healthCategory)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._healthCategory.ToString()) : null, "healthCategory" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._category)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._category.ToString()) : null, "category" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._severity)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._severity.ToString()) : null, "severity" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._source)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._source.ToString()) : null, "source" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._creationTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._creationTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "creationTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isCustomerResolvable ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isCustomerResolvable) : null, "isCustomerResolvable" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._summary)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._summary.ToString()) : null, "summary" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._caus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._caus.ToString()) : null, "causes" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._recommendation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recommendation.ToString()) : null, "recommendation" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.PowerShell.cs new file mode 100644 index 00000000000..9ce85911b36 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.PowerShell.cs @@ -0,0 +1,418 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Job model. + [System.ComponentModel.TypeConverter(typeof(JobModelTypeConverter))] + public partial class JobModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IJobModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new JobModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new JobModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal JobModel(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.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("ObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectId, global::System.Convert.ToString); + } + if (content.Contains("ObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectName = (string) content.GetValueForProperty("ObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectName, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalId = (string) content.GetValueForProperty("ObjectInternalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalId, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalName = (string) content.GetValueForProperty("ObjectInternalName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalName, global::System.Convert.ToString); + } + if (content.Contains("ObjectType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectType = (string) content.GetValueForProperty("ObjectType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectType, global::System.Convert.ToString); + } + if (content.Contains("ReplicationProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ReplicationProviderId = (string) content.GetValueForProperty("ReplicationProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ReplicationProviderId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("AllowedAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AllowedAction = (System.Collections.Generic.List) content.GetValueForProperty("AllowedAction",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AllowedAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ActivityId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ActivityId = (string) content.GetValueForProperty("ActivityId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ActivityId, global::System.Convert.ToString); + } + if (content.Contains("Task")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Task = (System.Collections.Generic.List) content.GetValueForProperty("Task",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Task, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Error = (System.Collections.Generic.List) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Error, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyAffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyAffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("CustomPropertyAffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyAffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyInstanceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailDescription, 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 JobModel(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.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("ObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectId, global::System.Convert.ToString); + } + if (content.Contains("ObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectName = (string) content.GetValueForProperty("ObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectName, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalId = (string) content.GetValueForProperty("ObjectInternalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalId, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalName = (string) content.GetValueForProperty("ObjectInternalName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectInternalName, global::System.Convert.ToString); + } + if (content.Contains("ObjectType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectType = (string) content.GetValueForProperty("ObjectType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ObjectType, global::System.Convert.ToString); + } + if (content.Contains("ReplicationProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ReplicationProviderId = (string) content.GetValueForProperty("ReplicationProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ReplicationProviderId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("AllowedAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AllowedAction = (System.Collections.Generic.List) content.GetValueForProperty("AllowedAction",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AllowedAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ActivityId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ActivityId = (string) content.GetValueForProperty("ActivityId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).ActivityId, global::System.Convert.ToString); + } + if (content.Contains("Task")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Task = (System.Collections.Generic.List) content.GetValueForProperty("Task",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Task, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Error = (System.Collections.Generic.List) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).Error, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyAffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyAffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("CustomPropertyAffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyAffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).CustomPropertyInstanceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal)this).AffectedObjectDetailDescription, 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.RecoveryServicesDataReplication.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(); + } + } + /// Job model. + [System.ComponentModel.TypeConverter(typeof(JobModelTypeConverter))] + public partial interface IJobModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.TypeConverter.cs new file mode 100644 index 00000000000..38738e2202a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class JobModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IJobModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return JobModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return JobModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return JobModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/JobModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.cs new file mode 100644 index 00000000000..2e84f752839 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.cs @@ -0,0 +1,562 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Job model. + public partial class JobModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Gets or sets the job activity id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ActivityId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ActivityId; } + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AffectedObjectDetailDescription; } + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AffectedObjectDetailType; } + + /// Gets or sets the list of allowed actions on the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AllowedAction { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AllowedAction; } + + /// Job model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Gets or sets the friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).DisplayName; } + + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? EndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).EndTime; } + + /// Gets or sets the list of errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Error { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).Error; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for ActivityId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ActivityId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ActivityId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ActivityId = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AffectedObjectDetailDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AffectedObjectDetailDescription = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AffectedObjectDetailType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AffectedObjectDetailType = value ?? null; } + + /// Internal Acessors for AllowedAction + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.AllowedAction { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AllowedAction; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).AllowedAction = value ?? null /* arrayOf */; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for CustomPropertyAffectedObjectDetail + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.CustomPropertyAffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomPropertyAffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).CustomPropertyAffectedObjectDetail = value ?? null /* model class */; } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).DisplayName = value ?? null; } + + /// Internal Acessors for EndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.EndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).EndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).EndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Error + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.Error { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).Error = value ?? null /* arrayOf */; } + + /// Internal Acessors for ObjectId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectId = value ?? null; } + + /// Internal Acessors for ObjectInternalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ObjectInternalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectInternalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectInternalId = value ?? null; } + + /// Internal Acessors for ObjectInternalName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ObjectInternalName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectInternalName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectInternalName = value ?? null; } + + /// Internal Acessors for ObjectName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ObjectName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectName = value ?? null; } + + /// Internal Acessors for ObjectType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ObjectType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectType = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ReplicationProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.ReplicationProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ReplicationProviderId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ReplicationProviderId = value ?? null; } + + /// Internal Acessors for SourceFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.SourceFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).SourceFabricProviderId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).SourceFabricProviderId = value ?? null; } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.StartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.State { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).State = value ?? null; } + + /// Internal Acessors for TargetFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.TargetFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).TargetFabricProviderId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).TargetFabricProviderId = value ?? null; } + + /// Internal Acessors for Task + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelInternal.Task { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).Task; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).Task = value ?? null /* arrayOf */; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Gets or sets the affected object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectId; } + + /// Gets or sets the affected object internal Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ObjectInternalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectInternalId; } + + /// Gets or sets the affected object internal name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ObjectInternalName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectInternalName; } + + /// Gets or sets the affected object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ObjectName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectName; } + + /// Gets or sets the object type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ObjectType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ObjectType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets or sets the replication provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ReplicationProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).ReplicationProviderId; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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); } + + /// Gets or sets the source fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SourceFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).SourceFabricProviderId; } + + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? StartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).StartTime; } + + /// Gets or sets the job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string State { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).State; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// Gets or sets the target fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string TargetFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).TargetFabricProviderId; } + + /// Gets or sets the list of tasks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Task { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)Property).Task; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public JobModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Job model. + public partial interface IJobModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets the job activity id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job activity id.", + SerializedName = @"activityId", + PossibleTypes = new [] { typeof(string) })] + string ActivityId { get; } + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Description of the affected object details.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string AffectedObjectDetailDescription { get; } + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Type of the affected object details.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string AffectedObjectDetailType { get; } + /// Gets or sets the list of allowed actions on the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of allowed actions on the job.", + SerializedName = @"allowedActions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AllowedAction { get; } + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for JobModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the end time.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; } + /// Gets or sets the list of errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of errors.", + SerializedName = @"errors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel) })] + System.Collections.Generic.List Error { get; } + /// Gets or sets the affected object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object Id.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string ObjectId { get; } + /// Gets or sets the affected object internal Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object internal Id.", + SerializedName = @"objectInternalId", + PossibleTypes = new [] { typeof(string) })] + string ObjectInternalId { get; } + /// Gets or sets the affected object internal name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object internal name.", + SerializedName = @"objectInternalName", + PossibleTypes = new [] { typeof(string) })] + string ObjectInternalName { get; } + /// Gets or sets the affected object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object name.", + SerializedName = @"objectName", + PossibleTypes = new [] { typeof(string) })] + string ObjectName { get; } + /// Gets or sets the object type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the object type.", + SerializedName = @"objectType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("AvsDiskPool", "FabricAgent", "Fabric", "Policy", "ProtectedItem", "RecoveryPlan", "ReplicationExtension", "Vault")] + string ObjectType { get; } + /// Gets or sets the provisioning state of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the job.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the replication provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the replication provider.", + SerializedName = @"replicationProviderId", + PossibleTypes = new [] { typeof(string) })] + string ReplicationProviderId { get; } + /// Gets or sets the source fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source fabric provider.", + SerializedName = @"sourceFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string SourceFabricProviderId { get; } + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the start time.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// Gets or sets the job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Pending", "Started", "Cancelling", "Succeeded", "Failed", "Cancelled", "CompletedWithInformation", "CompletedWithWarnings", "CompletedWithErrors")] + string State { get; } + /// Gets or sets the target fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric provider.", + SerializedName = @"targetFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricProviderId { get; } + /// Gets or sets the list of tasks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of tasks.", + SerializedName = @"tasks", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel) })] + System.Collections.Generic.List Task { get; } + + } + /// Job model. + internal partial interface IJobModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Gets or sets the job activity id. + string ActivityId { get; set; } + /// Description of the affected object details. + string AffectedObjectDetailDescription { get; set; } + /// Type of the affected object details. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string AffectedObjectDetailType { get; set; } + /// Gets or sets the list of allowed actions on the job. + System.Collections.Generic.List AllowedAction { get; set; } + /// Job model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties CustomProperty { get; set; } + /// Gets or sets any custom properties of the affected object. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails CustomPropertyAffectedObjectDetail { get; set; } + /// Discriminator property for JobModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the friendly display name. + string DisplayName { get; set; } + /// Gets or sets the end time. + global::System.DateTime? EndTime { get; set; } + /// Gets or sets the list of errors. + System.Collections.Generic.List Error { get; set; } + /// Gets or sets the affected object Id. + string ObjectId { get; set; } + /// Gets or sets the affected object internal Id. + string ObjectInternalId { get; set; } + /// Gets or sets the affected object internal name. + string ObjectInternalName { get; set; } + /// Gets or sets the affected object name. + string ObjectName { get; set; } + /// Gets or sets the object type. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("AvsDiskPool", "FabricAgent", "Fabric", "Policy", "ProtectedItem", "RecoveryPlan", "ReplicationExtension", "Vault")] + string ObjectType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the job. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the replication provider. + string ReplicationProviderId { get; set; } + /// Gets or sets the source fabric provider. + string SourceFabricProviderId { get; set; } + /// Gets or sets the start time. + global::System.DateTime? StartTime { get; set; } + /// Gets or sets the job state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Pending", "Started", "Cancelling", "Succeeded", "Failed", "Cancelled", "CompletedWithInformation", "CompletedWithWarnings", "CompletedWithErrors")] + string State { get; set; } + /// Gets or sets the target fabric provider. + string TargetFabricProviderId { get; set; } + /// Gets or sets the list of tasks. + System.Collections.Generic.List Task { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.json.cs new file mode 100644 index 00000000000..5403f6902b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Job model. + public partial class JobModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new JobModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal JobModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..2bffa5ccec0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Job model custom properties. + [System.ComponentModel.TypeConverter(typeof(JobModelCustomPropertiesTypeConverter))] + public partial class JobModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IJobModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new JobModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new JobModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal JobModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, 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 JobModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, 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.RecoveryServicesDataReplication.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(); + } + } + /// Job model custom properties. + [System.ComponentModel.TypeConverter(typeof(JobModelCustomPropertiesTypeConverter))] + public partial interface IJobModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..7a83b40bb38 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class JobModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IJobModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return JobModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return JobModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return JobModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.cs new file mode 100644 index 00000000000..cc7ea0dc6d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Job model custom properties. + public partial class JobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails _affectedObjectDetail; + + /// Gets or sets any custom properties of the affected object. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails AffectedObjectDetail { get => (this._affectedObjectDetail = this._affectedObjectDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetails()); } + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)AffectedObjectDetail).Description; } + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)AffectedObjectDetail).Type; } + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Internal Acessors for AffectedObjectDetail + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetail { get => (this._affectedObjectDetail = this._affectedObjectDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetails()); set { {_affectedObjectDetail = value;} } } + + /// Internal Acessors for AffectedObjectDetailDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)AffectedObjectDetail).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)AffectedObjectDetail).Description = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)AffectedObjectDetail).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetailsInternal)AffectedObjectDetail).Type = value ?? null; } + + /// Creates an new instance. + public JobModelCustomProperties() + { + + } + } + /// Job model custom properties. + public partial interface IJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Description of the affected object details.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string AffectedObjectDetailDescription { get; } + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Type of the affected object details.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string AffectedObjectDetailType { get; } + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for JobModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Job model custom properties. + internal partial interface IJobModelCustomPropertiesInternal + + { + /// Gets or sets any custom properties of the affected object. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails AffectedObjectDetail { get; set; } + /// Description of the affected object details. + string AffectedObjectDetailDescription { get; set; } + /// Type of the affected object details. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string AffectedObjectDetailType { get; set; } + /// Discriminator property for JobModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.json.cs new file mode 100644 index 00000000000..3e5cebc2700 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelCustomProperties.json.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Job model custom properties. + public partial class JobModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties interface + /// is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "FailoverJobDetails": + { + return new FailoverJobModelCustomProperties(json); + } + case "TestFailoverCleanupJobDetails": + { + return new TestFailoverCleanupJobModelCustomProperties(json); + } + case "TestFailoverJobDetails": + { + return new TestFailoverJobModelCustomProperties(json); + } + } + return new JobModelCustomProperties(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal JobModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_affectedObjectDetail = If( json?.PropertyT("affectedObjectDetails"), out var __jsonAffectedObjectDetails) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetails.FromJson(__jsonAffectedObjectDetails) : _affectedObjectDetail;} + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._affectedObjectDetail ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._affectedObjectDetail.ToJson(null,serializationMode) : null, "affectedObjectDetails" ,container.Add ); + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.PowerShell.cs new file mode 100644 index 00000000000..0023a242475 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a JobModel list operation. + [System.ComponentModel.TypeConverter(typeof(JobModelListResultTypeConverter))] + public partial class JobModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IJobModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new JobModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new JobModelListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal JobModelListResult(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.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)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 JobModelListResult(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.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal)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.RecoveryServicesDataReplication.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 JobModel list operation. + [System.ComponentModel.TypeConverter(typeof(JobModelListResultTypeConverter))] + public partial interface IJobModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..e1b24d06440 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class JobModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IJobModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return JobModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return JobModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return JobModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.cs new file mode 100644 index 00000000000..6dbaec36b8d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a JobModel list operation. + public partial class JobModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The JobModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public JobModelListResult() + { + + } + } + /// The response of a JobModel list operation. + public partial interface IJobModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 JobModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The JobModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a JobModel list operation. + internal partial interface IJobModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The JobModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.json.cs new file mode 100644 index 00000000000..4e53b578ebf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a JobModel list operation. + public partial class JobModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new JobModelListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal JobModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModel.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.PowerShell.cs new file mode 100644 index 00000000000..8dd9d01f97a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.PowerShell.cs @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Job model properties. + [System.ComponentModel.TypeConverter(typeof(JobModelPropertiesTypeConverter))] + public partial class JobModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IJobModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new JobModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new JobModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal JobModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("ObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectId, global::System.Convert.ToString); + } + if (content.Contains("ObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectName = (string) content.GetValueForProperty("ObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectName, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalId = (string) content.GetValueForProperty("ObjectInternalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalId, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalName = (string) content.GetValueForProperty("ObjectInternalName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalName, global::System.Convert.ToString); + } + if (content.Contains("ObjectType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectType = (string) content.GetValueForProperty("ObjectType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectType, global::System.Convert.ToString); + } + if (content.Contains("ReplicationProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ReplicationProviderId = (string) content.GetValueForProperty("ReplicationProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ReplicationProviderId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("AllowedAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AllowedAction = (System.Collections.Generic.List) content.GetValueForProperty("AllowedAction",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AllowedAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ActivityId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ActivityId = (string) content.GetValueForProperty("ActivityId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ActivityId, global::System.Convert.ToString); + } + if (content.Contains("Task")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Task = (System.Collections.Generic.List) content.GetValueForProperty("Task",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Task, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Error = (System.Collections.Generic.List) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Error, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyAffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyAffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("CustomPropertyAffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyAffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyInstanceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailDescription, 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 JobModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("ObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectId, global::System.Convert.ToString); + } + if (content.Contains("ObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectName = (string) content.GetValueForProperty("ObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectName, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalId = (string) content.GetValueForProperty("ObjectInternalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalId, global::System.Convert.ToString); + } + if (content.Contains("ObjectInternalName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalName = (string) content.GetValueForProperty("ObjectInternalName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectInternalName, global::System.Convert.ToString); + } + if (content.Contains("ObjectType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectType = (string) content.GetValueForProperty("ObjectType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ObjectType, global::System.Convert.ToString); + } + if (content.Contains("ReplicationProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ReplicationProviderId = (string) content.GetValueForProperty("ReplicationProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ReplicationProviderId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("AllowedAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AllowedAction = (System.Collections.Generic.List) content.GetValueForProperty("AllowedAction",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AllowedAction, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ActivityId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ActivityId = (string) content.GetValueForProperty("ActivityId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ActivityId, global::System.Convert.ToString); + } + if (content.Contains("Task")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Task = (System.Collections.Generic.List) content.GetValueForProperty("Task",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Task, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Error = (System.Collections.Generic.List) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).Error, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyAffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyAffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("CustomPropertyAffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyAffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).CustomPropertyInstanceType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal)this).AffectedObjectDetailDescription, 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.RecoveryServicesDataReplication.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(); + } + } + /// Job model properties. + [System.ComponentModel.TypeConverter(typeof(JobModelPropertiesTypeConverter))] + public partial interface IJobModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..64de60195fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class JobModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IJobModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return JobModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return JobModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return JobModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.cs new file mode 100644 index 00000000000..54b8d36a8c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Job model properties. + public partial class JobModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal + { + + /// Backing field for property. + private string _activityId; + + /// Gets or sets the job activity id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ActivityId { get => this._activityId; } + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetailDescription; } + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetailType; } + + /// Backing field for property. + private System.Collections.Generic.List _allowedAction; + + /// Gets or sets the list of allowed actions on the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List AllowedAction { get => this._allowedAction; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties _customProperty; + + /// Job model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Backing field for property. + private string _displayName; + + /// Gets or sets the friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; } + + /// Backing field for property. + private global::System.DateTime? _endTime; + + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? EndTime { get => this._endTime; } + + /// Backing field for property. + private System.Collections.Generic.List _error; + + /// Gets or sets the list of errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Error { get => this._error; } + + /// Internal Acessors for ActivityId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ActivityId { get => this._activityId; set { {_activityId = value;} } } + + /// Internal Acessors for AffectedObjectDetailDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetailDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetailDescription = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetailType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetailType = value ?? null; } + + /// Internal Acessors for AllowedAction + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.AllowedAction { get => this._allowedAction; set { {_allowedAction = value;} } } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for CustomPropertyAffectedObjectDetail + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.CustomPropertyAffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)CustomProperty).AffectedObjectDetail = value ?? null /* model class */; } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.DisplayName { get => this._displayName; set { {_displayName = value;} } } + + /// Internal Acessors for EndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.EndTime { get => this._endTime; set { {_endTime = value;} } } + + /// Internal Acessors for Error + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.Error { get => this._error; set { {_error = value;} } } + + /// Internal Acessors for ObjectId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ObjectId { get => this._objectId; set { {_objectId = value;} } } + + /// Internal Acessors for ObjectInternalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ObjectInternalId { get => this._objectInternalId; set { {_objectInternalId = value;} } } + + /// Internal Acessors for ObjectInternalName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ObjectInternalName { get => this._objectInternalName; set { {_objectInternalName = value;} } } + + /// Internal Acessors for ObjectName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ObjectName { get => this._objectName; set { {_objectName = value;} } } + + /// Internal Acessors for ObjectType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ObjectType { get => this._objectType; set { {_objectType = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for ReplicationProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.ReplicationProviderId { get => this._replicationProviderId; set { {_replicationProviderId = value;} } } + + /// Internal Acessors for SourceFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.SourceFabricProviderId { get => this._sourceFabricProviderId; set { {_sourceFabricProviderId = value;} } } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.StartTime { get => this._startTime; set { {_startTime = value;} } } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.State { get => this._state; set { {_state = value;} } } + + /// Internal Acessors for TargetFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.TargetFabricProviderId { get => this._targetFabricProviderId; set { {_targetFabricProviderId = value;} } } + + /// Internal Acessors for Task + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelPropertiesInternal.Task { get => this._task; set { {_task = value;} } } + + /// Backing field for property. + private string _objectId; + + /// Gets or sets the affected object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ObjectId { get => this._objectId; } + + /// Backing field for property. + private string _objectInternalId; + + /// Gets or sets the affected object internal Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ObjectInternalId { get => this._objectInternalId; } + + /// Backing field for property. + private string _objectInternalName; + + /// Gets or sets the affected object internal name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ObjectInternalName { get => this._objectInternalName; } + + /// Backing field for property. + private string _objectName; + + /// Gets or sets the affected object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ObjectName { get => this._objectName; } + + /// Backing field for property. + private string _objectType; + + /// Gets or sets the object type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ObjectType { get => this._objectType; } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _replicationProviderId; + + /// Gets or sets the replication provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ReplicationProviderId { get => this._replicationProviderId; } + + /// Backing field for property. + private string _sourceFabricProviderId; + + /// Gets or sets the source fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceFabricProviderId { get => this._sourceFabricProviderId; } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; } + + /// Backing field for property. + private string _state; + + /// Gets or sets the job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string State { get => this._state; } + + /// Backing field for property. + private string _targetFabricProviderId; + + /// Gets or sets the target fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetFabricProviderId { get => this._targetFabricProviderId; } + + /// Backing field for property. + private System.Collections.Generic.List _task; + + /// Gets or sets the list of tasks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Task { get => this._task; } + + /// Creates an new instance. + public JobModelProperties() + { + + } + } + /// Job model properties. + public partial interface IJobModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the job activity id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job activity id.", + SerializedName = @"activityId", + PossibleTypes = new [] { typeof(string) })] + string ActivityId { get; } + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Description of the affected object details.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string AffectedObjectDetailDescription { get; } + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Type of the affected object details.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string AffectedObjectDetailType { get; } + /// Gets or sets the list of allowed actions on the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of allowed actions on the job.", + SerializedName = @"allowedActions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AllowedAction { get; } + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for JobModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the end time.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; } + /// Gets or sets the list of errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of errors.", + SerializedName = @"errors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel) })] + System.Collections.Generic.List Error { get; } + /// Gets or sets the affected object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object Id.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string ObjectId { get; } + /// Gets or sets the affected object internal Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object internal Id.", + SerializedName = @"objectInternalId", + PossibleTypes = new [] { typeof(string) })] + string ObjectInternalId { get; } + /// Gets or sets the affected object internal name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object internal name.", + SerializedName = @"objectInternalName", + PossibleTypes = new [] { typeof(string) })] + string ObjectInternalName { get; } + /// Gets or sets the affected object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the affected object name.", + SerializedName = @"objectName", + PossibleTypes = new [] { typeof(string) })] + string ObjectName { get; } + /// Gets or sets the object type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the object type.", + SerializedName = @"objectType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("AvsDiskPool", "FabricAgent", "Fabric", "Policy", "ProtectedItem", "RecoveryPlan", "ReplicationExtension", "Vault")] + string ObjectType { get; } + /// Gets or sets the provisioning state of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the job.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the replication provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the replication provider.", + SerializedName = @"replicationProviderId", + PossibleTypes = new [] { typeof(string) })] + string ReplicationProviderId { get; } + /// Gets or sets the source fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source fabric provider.", + SerializedName = @"sourceFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string SourceFabricProviderId { get; } + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the start time.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// Gets or sets the job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Pending", "Started", "Cancelling", "Succeeded", "Failed", "Cancelled", "CompletedWithInformation", "CompletedWithWarnings", "CompletedWithErrors")] + string State { get; } + /// Gets or sets the target fabric provider. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric provider.", + SerializedName = @"targetFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricProviderId { get; } + /// Gets or sets the list of tasks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of tasks.", + SerializedName = @"tasks", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel) })] + System.Collections.Generic.List Task { get; } + + } + /// Job model properties. + internal partial interface IJobModelPropertiesInternal + + { + /// Gets or sets the job activity id. + string ActivityId { get; set; } + /// Description of the affected object details. + string AffectedObjectDetailDescription { get; set; } + /// Type of the affected object details. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("object")] + string AffectedObjectDetailType { get; set; } + /// Gets or sets the list of allowed actions on the job. + System.Collections.Generic.List AllowedAction { get; set; } + /// Job model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties CustomProperty { get; set; } + /// Gets or sets any custom properties of the affected object. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails CustomPropertyAffectedObjectDetail { get; set; } + /// Discriminator property for JobModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the friendly display name. + string DisplayName { get; set; } + /// Gets or sets the end time. + global::System.DateTime? EndTime { get; set; } + /// Gets or sets the list of errors. + System.Collections.Generic.List Error { get; set; } + /// Gets or sets the affected object Id. + string ObjectId { get; set; } + /// Gets or sets the affected object internal Id. + string ObjectInternalId { get; set; } + /// Gets or sets the affected object internal name. + string ObjectInternalName { get; set; } + /// Gets or sets the affected object name. + string ObjectName { get; set; } + /// Gets or sets the object type. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("AvsDiskPool", "FabricAgent", "Fabric", "Policy", "ProtectedItem", "RecoveryPlan", "ReplicationExtension", "Vault")] + string ObjectType { get; set; } + /// Gets or sets the provisioning state of the job. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the replication provider. + string ReplicationProviderId { get; set; } + /// Gets or sets the source fabric provider. + string SourceFabricProviderId { get; set; } + /// Gets or sets the start time. + global::System.DateTime? StartTime { get; set; } + /// Gets or sets the job state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Pending", "Started", "Cancelling", "Succeeded", "Failed", "Cancelled", "CompletedWithInformation", "CompletedWithWarnings", "CompletedWithErrors")] + string State { get; set; } + /// Gets or sets the target fabric provider. + string TargetFabricProviderId { get; set; } + /// Gets or sets the list of tasks. + System.Collections.Generic.List Task { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.json.cs new file mode 100644 index 00000000000..1713f26832e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/JobModelProperties.json.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Job model properties. + public partial class JobModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new JobModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal JobModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? global::System.DateTime.TryParse((string)__jsonEndTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndTimeValue) ? __jsonEndTimeValue : _endTime : _endTime;} + {_objectId = If( json?.PropertyT("objectId"), out var __jsonObjectId) ? (string)__jsonObjectId : (string)_objectId;} + {_objectName = If( json?.PropertyT("objectName"), out var __jsonObjectName) ? (string)__jsonObjectName : (string)_objectName;} + {_objectInternalId = If( json?.PropertyT("objectInternalId"), out var __jsonObjectInternalId) ? (string)__jsonObjectInternalId : (string)_objectInternalId;} + {_objectInternalName = If( json?.PropertyT("objectInternalName"), out var __jsonObjectInternalName) ? (string)__jsonObjectInternalName : (string)_objectInternalName;} + {_objectType = If( json?.PropertyT("objectType"), out var __jsonObjectType) ? (string)__jsonObjectType : (string)_objectType;} + {_replicationProviderId = If( json?.PropertyT("replicationProviderId"), out var __jsonReplicationProviderId) ? (string)__jsonReplicationProviderId : (string)_replicationProviderId;} + {_sourceFabricProviderId = If( json?.PropertyT("sourceFabricProviderId"), out var __jsonSourceFabricProviderId) ? (string)__jsonSourceFabricProviderId : (string)_sourceFabricProviderId;} + {_targetFabricProviderId = If( json?.PropertyT("targetFabricProviderId"), out var __jsonTargetFabricProviderId) ? (string)__jsonTargetFabricProviderId : (string)_targetFabricProviderId;} + {_allowedAction = If( json?.PropertyT("allowedActions"), out var __jsonAllowedActions) ? If( __jsonAllowedActions as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _allowedAction;} + {_activityId = If( json?.PropertyT("activityId"), out var __jsonActivityId) ? (string)__jsonActivityId : (string)_activityId;} + {_task = If( json?.PropertyT("tasks"), out var __jsonTasks) ? If( __jsonTasks as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ITaskModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModel.FromJson(__p) )) ))() : null : _task;} + {_error = If( json?.PropertyT("errors"), out var __jsonErrors) ? If( __jsonErrors as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IErrorModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ErrorModel.FromJson(__k) )) ))() : null : _error;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._endTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._endTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._objectId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._objectId.ToString()) : null, "objectId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._objectName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._objectName.ToString()) : null, "objectName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._objectInternalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._objectInternalId.ToString()) : null, "objectInternalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._objectInternalName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._objectInternalName.ToString()) : null, "objectInternalName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._objectType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._objectType.ToString()) : null, "objectType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._replicationProviderId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._replicationProviderId.ToString()) : null, "replicationProviderId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceFabricProviderId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceFabricProviderId.ToString()) : null, "sourceFabricProviderId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetFabricProviderId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetFabricProviderId.ToString()) : null, "targetFabricProviderId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._allowedAction) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._allowedAction ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("allowedActions",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._activityId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._activityId.ToString()) : null, "activityId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._task) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._task ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("tasks",__r); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._error) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __n in this._error ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("errors",__m); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs new file mode 100644 index 00000000000..1861de53873 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IManagedServiceIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs new file mode 100644 index 00000000000..0c0eeaa51df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IManagedServiceIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs new file mode 100644 index 00000000000..5bb6b129fc8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentity : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities _userAssignedIdentity; + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get => (this._userAssignedIdentity = this._userAssignedIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentities()); 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities 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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs new file mode 100644 index 00000000000..15dfec03fa7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ManagedServiceIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedServiceIdentity(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentities.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != this._userAssignedIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs new file mode 100644 index 00000000000..8a9d491ddc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedServiceIdentityUserAssignedIdentities(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 ManagedServiceIdentityUserAssignedIdentities(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.RecoveryServicesDataReplication.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 identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial interface IManagedServiceIdentityUserAssignedIdentities + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs new file mode 100644 index 00000000000..05ddada3f94 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedServiceIdentityUserAssignedIdentitiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedServiceIdentityUserAssignedIdentities.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs new file mode 100644 index 00000000000..33a9465545a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentitiesInternal + { + + /// + /// Creates an new instance. + /// + public ManagedServiceIdentityUserAssignedIdentities() + { + + } + } + /// The identities assigned to this resource by the user. + public partial interface IManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + + } + /// The identities assigned to this resource by the user. + internal partial interface IManagedServiceIdentityUserAssignedIdentitiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs new file mode 100644 index 00000000000..bf01fa5e955 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IUserAssignedIdentity value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentities source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs new file mode 100644 index 00000000000..18c3ecacf7d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ManagedServiceIdentityUserAssignedIdentities(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedServiceIdentityUserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.UserAssignedIdentity.FromJson(j) ,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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..33fe3ed6ddd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..845a8659abf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..b504c6e4cc6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationDisplay()); set => this._display = value; } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for ActionType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.ActionType { get => this._actionType; set { {_actionType = value;} } } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Description = value ?? null; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Operation = value ?? null; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Provider = value ?? null; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)Display).Resource = value ?? null; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..99421b292b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..ba8ca530a00 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..84cfedf92aa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..5e1766e7829 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..46cf1de9ef3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..4ab84f5e537 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..62d54d7a817 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..4fe5f2c0591 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..580fc3bf4d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.PowerShell.cs new file mode 100644 index 00000000000..e1532b1a619 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.PowerShell.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Defines the operation status. + [System.ComponentModel.TypeConverter(typeof(OperationStatusTypeConverter))] + public partial class OperationStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IOperationStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).StartTime = (string) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).StartTime, global::System.Convert.ToString); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).EndTime = (string) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).EndTime, 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 OperationStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).StartTime = (string) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).StartTime, global::System.Convert.ToString); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).EndTime = (string) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal)this).EndTime, 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.RecoveryServicesDataReplication.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 operation status. + [System.ComponentModel.TypeConverter(typeof(OperationStatusTypeConverter))] + public partial interface IOperationStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.TypeConverter.cs new file mode 100644 index 00000000000..1ce763dc9e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IOperationStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.cs new file mode 100644 index 00000000000..67bf4bfcbad --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Defines the operation status. + public partial class OperationStatus : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatusInternal + { + + /// Backing field for property. + private string _endTime; + + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EndTime { get => this._endTime; set => this._endTime = value; } + + /// Backing field for property. + private string _id; + + /// Gets or sets the Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _name; + + /// Gets or sets the operation name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 _startTime; + + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StartTime { get => this._startTime; set => this._startTime = value; } + + /// Backing field for property. + private string _status; + + /// + /// Gets or sets the status of the operation. ARM expects the terminal status to be one of Succeeded/ Failed/ Canceled. All + /// other values imply that the operation is still running. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// Creates an new instance. + public OperationStatus() + { + + } + } + /// Defines the operation status. + public partial interface IOperationStatus : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the end time.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(string) })] + string EndTime { get; set; } + /// Gets or sets the Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Gets or sets the operation name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the operation name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the start time.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(string) })] + string StartTime { get; set; } + /// + /// Gets or sets the status of the operation. ARM expects the terminal status to be one of Succeeded/ Failed/ Canceled. All + /// other values imply that the operation is still running. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the status of the operation. ARM expects the terminal status to be one of Succeeded/ Failed/ Canceled. All other values imply that the operation is still running.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + string Status { get; set; } + + } + /// Defines the operation status. + internal partial interface IOperationStatusInternal + + { + /// Gets or sets the end time. + string EndTime { get; set; } + /// Gets or sets the Id. + string Id { get; set; } + /// Gets or sets the operation name. + string Name { get; set; } + /// Gets or sets the start time. + string StartTime { get; set; } + /// + /// Gets or sets the status of the operation. ARM expects the terminal status to be one of Succeeded/ Failed/ Canceled. All + /// other values imply that the operation is still running. + /// + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.json.cs new file mode 100644 index 00000000000..60e2c0c8a17 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/OperationStatus.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Defines the operation status. + public partial class OperationStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new OperationStatus(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal OperationStatus(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? (string)__jsonStartTime : (string)_startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? (string)__jsonEndTime : (string)_endTime;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + AddIf( null != (((object)this._startTime)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._startTime.ToString()) : null, "startTime" ,container.Add ); + AddIf( null != (((object)this._endTime)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._endTime.ToString()) : null, "endTime" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.PowerShell.cs new file mode 100644 index 00000000000..a81599205a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Planned failover model. + [System.ComponentModel.TypeConverter(typeof(PlannedFailoverModelTypeConverter))] + public partial class PlannedFailoverModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PlannedFailoverModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PlannedFailoverModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PlannedFailoverModel(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.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomPropertyInstanceType, 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 PlannedFailoverModel(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.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Planned failover model. + [System.ComponentModel.TypeConverter(typeof(PlannedFailoverModelTypeConverter))] + public partial interface IPlannedFailoverModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.TypeConverter.cs new file mode 100644 index 00000000000..25410887021 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PlannedFailoverModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PlannedFailoverModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PlannedFailoverModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PlannedFailoverModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.cs new file mode 100644 index 00000000000..7a9fd3ac914 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Planned failover model. + public partial class PlannedFailoverModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal + { + + /// Planned failover model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)Property).CustomPropertyInstanceType = value ; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelProperties()); set { {_property = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties _property; + + /// Planned failover model properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelProperties()); set => this._property = value; } + + /// Creates an new instance. + public PlannedFailoverModel() + { + + } + } + /// Planned failover model. + public partial interface IPlannedFailoverModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for PlannedFailoverModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + + } + /// Planned failover model. + internal partial interface IPlannedFailoverModelInternal + + { + /// Planned failover model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for PlannedFailoverModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Planned failover model properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties Property { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.json.cs new file mode 100644 index 00000000000..1b896e625f5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Planned failover model. + public partial class PlannedFailoverModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PlannedFailoverModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PlannedFailoverModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.PlannedFailoverModelProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..8e77883a157 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.PowerShell.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Planned failover model custom properties. + [System.ComponentModel.TypeConverter(typeof(PlannedFailoverModelCustomPropertiesTypeConverter))] + public partial class PlannedFailoverModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PlannedFailoverModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PlannedFailoverModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PlannedFailoverModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType, 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 PlannedFailoverModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Planned failover model custom properties. + [System.ComponentModel.TypeConverter(typeof(PlannedFailoverModelCustomPropertiesTypeConverter))] + public partial interface IPlannedFailoverModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..65999257380 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PlannedFailoverModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PlannedFailoverModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PlannedFailoverModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PlannedFailoverModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.cs new file mode 100644 index 00000000000..7a319cc88b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Planned failover model custom properties. + public partial class PlannedFailoverModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public PlannedFailoverModelCustomProperties() + { + + } + } + /// Planned failover model custom properties. + public partial interface IPlannedFailoverModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for PlannedFailoverModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Planned failover model custom properties. + internal partial interface IPlannedFailoverModelCustomPropertiesInternal + + { + /// Discriminator property for PlannedFailoverModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.json.cs new file mode 100644 index 00000000000..35dedbded2a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelCustomProperties.json.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Planned failover model custom properties. + public partial class PlannedFailoverModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties + /// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the + /// payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHciplannedFailoverModelCustomProperties(json); + } + case "VMwareToAzStackHCI": + { + return new VMwareToAzStackHciplannedFailoverModelCustomProperties(json); + } + } + return new PlannedFailoverModelCustomProperties(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PlannedFailoverModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.PowerShell.cs new file mode 100644 index 00000000000..ba6df6ae8d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Planned failover model properties. + [System.ComponentModel.TypeConverter(typeof(PlannedFailoverModelPropertiesTypeConverter))] + public partial class PlannedFailoverModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PlannedFailoverModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PlannedFailoverModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PlannedFailoverModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomPropertyInstanceType, 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 PlannedFailoverModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Planned failover model properties. + [System.ComponentModel.TypeConverter(typeof(PlannedFailoverModelPropertiesTypeConverter))] + public partial interface IPlannedFailoverModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..0fca6e2fe75 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PlannedFailoverModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PlannedFailoverModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PlannedFailoverModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PlannedFailoverModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.cs new file mode 100644 index 00000000000..eb6c457d184 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Planned failover model properties. + public partial class PlannedFailoverModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties _customProperty; + + /// Planned failover model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties()); set { {_customProperty = value;} } } + + /// Creates an new instance. + public PlannedFailoverModelProperties() + { + + } + } + /// Planned failover model properties. + public partial interface IPlannedFailoverModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for PlannedFailoverModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + + } + /// Planned failover model properties. + internal partial interface IPlannedFailoverModelPropertiesInternal + + { + /// Planned failover model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for PlannedFailoverModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.json.cs new file mode 100644 index 00000000000..ad7860b6515 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PlannedFailoverModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Planned failover model properties. + public partial class PlannedFailoverModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PlannedFailoverModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PlannedFailoverModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.PowerShell.cs new file mode 100644 index 00000000000..d949c48dea4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.PowerShell.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Policy model. + [System.ComponentModel.TypeConverter(typeof(PolicyModelTypeConverter))] + public partial class PolicyModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPolicyModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PolicyModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PolicyModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PolicyModel(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.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomPropertyInstanceType, 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 PolicyModel(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.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Policy model. + [System.ComponentModel.TypeConverter(typeof(PolicyModelTypeConverter))] + public partial interface IPolicyModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.TypeConverter.cs new file mode 100644 index 00000000000..636132acdb3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PolicyModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPolicyModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PolicyModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PolicyModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PolicyModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.cs new file mode 100644 index 00000000000..8caad508fe7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Policy model. + public partial class PolicyModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Policy model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the policy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public PolicyModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Policy model. + public partial interface IPolicyModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the policy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the policy.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Policy model. + internal partial interface IPolicyModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Policy model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for PolicyModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the policy. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.json.cs new file mode 100644 index 00000000000..c03d86d66f5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Policy model. + public partial class PolicyModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PolicyModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PolicyModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..76063edeccf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Policy model custom properties. + [System.ComponentModel.TypeConverter(typeof(PolicyModelCustomPropertiesTypeConverter))] + public partial class PolicyModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PolicyModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PolicyModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PolicyModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType, 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 PolicyModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Policy model custom properties. + [System.ComponentModel.TypeConverter(typeof(PolicyModelCustomPropertiesTypeConverter))] + public partial interface IPolicyModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..55639c25560 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PolicyModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PolicyModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PolicyModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PolicyModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.cs new file mode 100644 index 00000000000..494013fc858 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Policy model custom properties. + public partial class PolicyModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public PolicyModelCustomProperties() + { + + } + } + /// Policy model custom properties. + public partial interface IPolicyModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Policy model custom properties. + internal partial interface IPolicyModelCustomPropertiesInternal + + { + /// Discriminator property for PolicyModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.json.cs new file mode 100644 index 00000000000..f2b6ae7e67c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Policy model custom properties. + public partial class PolicyModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties interface + /// is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHcipolicyModelCustomProperties(json); + } + case "VMwareToAzStackHCI": + { + return new VMwareToAzStackHcipolicyModelCustomProperties(json); + } + } + return new PolicyModelCustomProperties(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PolicyModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.PowerShell.cs new file mode 100644 index 00000000000..22d4c4f567e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a PolicyModel list operation. + [System.ComponentModel.TypeConverter(typeof(PolicyModelListResultTypeConverter))] + public partial class PolicyModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPolicyModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PolicyModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PolicyModelListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PolicyModelListResult(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.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)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 PolicyModelListResult(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.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal)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.RecoveryServicesDataReplication.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 PolicyModel list operation. + [System.ComponentModel.TypeConverter(typeof(PolicyModelListResultTypeConverter))] + public partial interface IPolicyModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..a7e6336a5d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PolicyModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPolicyModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PolicyModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PolicyModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PolicyModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.cs new file mode 100644 index 00000000000..1912e457435 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PolicyModel list operation. + public partial class PolicyModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The PolicyModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PolicyModelListResult() + { + + } + } + /// The response of a PolicyModel list operation. + public partial interface IPolicyModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PolicyModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The PolicyModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a PolicyModel list operation. + internal partial interface IPolicyModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The PolicyModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.json.cs new file mode 100644 index 00000000000..015ab3c1e74 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PolicyModel list operation. + public partial class PolicyModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PolicyModelListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PolicyModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.PowerShell.cs new file mode 100644 index 00000000000..98ba197fe27 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Policy model properties. + [System.ComponentModel.TypeConverter(typeof(PolicyModelPropertiesTypeConverter))] + public partial class PolicyModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPolicyModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PolicyModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PolicyModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PolicyModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomPropertyInstanceType, 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 PolicyModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Policy model properties. + [System.ComponentModel.TypeConverter(typeof(PolicyModelPropertiesTypeConverter))] + public partial interface IPolicyModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..2b08215ac88 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PolicyModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPolicyModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PolicyModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PolicyModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PolicyModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.cs new file mode 100644 index 00000000000..7494894cae7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Policy model properties. + public partial class PolicyModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties _customProperty; + + /// Policy model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the policy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Creates an new instance. + public PolicyModelProperties() + { + + } + } + /// Policy model properties. + public partial interface IPolicyModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the policy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the policy.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Policy model properties. + internal partial interface IPolicyModelPropertiesInternal + + { + /// Policy model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for PolicyModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the policy. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.json.cs new file mode 100644 index 00000000000..22696172536 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PolicyModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Policy model properties. + public partial class PolicyModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PolicyModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PolicyModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.PowerShell.cs new file mode 100644 index 00000000000..6e3aac46fba --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.PowerShell.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + /// + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointTypeConverter))] + public partial class PrivateEndpoint + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpoint DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpoint(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpoint(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpoint(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal)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 PrivateEndpoint(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal)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.RecoveryServicesDataReplication.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(); + } + } + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointTypeConverter))] + public partial interface IPrivateEndpoint + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.TypeConverter.cs new file mode 100644 index 00000000000..a0916da95e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpoint ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpoint.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpoint.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpoint.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.cs new file mode 100644 index 00000000000..64cc96e84f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + /// + public partial class PrivateEndpoint : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal + { + + /// Backing field for property. + private string _id; + + /// Gets or sets the id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Creates an new instance. + public PrivateEndpoint() + { + + } + } + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + public partial interface IPrivateEndpoint : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + + } + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + internal partial interface IPrivateEndpointInternal + + { + /// Gets or sets the id. + string Id { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.json.cs new file mode 100644 index 00000000000..5a999377a1a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpoint.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + /// + public partial class PrivateEndpoint + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpoint(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpoint(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.PowerShell.cs new file mode 100644 index 00000000000..728a528a7a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.PowerShell.cs @@ -0,0 +1,300 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents private endpoint connection. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionTypeConverter))] + public partial class PrivateEndpointConnection + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnection(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnection(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnection(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionResponsePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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 PrivateEndpointConnection(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionResponsePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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.RecoveryServicesDataReplication.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(); + } + } + /// Represents private endpoint connection. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionTypeConverter))] + public partial interface IPrivateEndpointConnection + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.TypeConverter.cs new file mode 100644 index 00000000000..7749cbe62ff --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnection.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnection.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.cs new file mode 100644 index 00000000000..6e0edbd290d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private endpoint connection. + public partial class PrivateEndpointConnection : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for PrivateEndpoint + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal.PrivateEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateEndpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateEndpoint = value ?? null /* model class */; } + + /// Internal Acessors for PrivateLinkServiceConnectionState + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal.PrivateLinkServiceConnectionState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionState = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionResponseProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Gets or sets the id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateEndpointId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateEndpointId = value ?? null; } + + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionStateActionsRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionStateActionsRequired = value ?? null; } + + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionStateDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionStateDescription = value ?? null; } + + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionStateStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).PrivateLinkServiceConnectionStateStatus = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionResponseProperties()); set => this._property = value; } + + /// Gets or sets provisioning state of the private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public PrivateEndpointConnection() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Represents private endpoint connection. + public partial interface IPrivateEndpointConnection : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets the id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointId { get; set; } + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets actions required.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the status.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// Gets or sets provisioning state of the private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets provisioning state of the private endpoint connection.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Represents private endpoint connection. + internal partial interface IPrivateEndpointConnectionInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + /// + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint PrivateEndpoint { get; set; } + /// Gets or sets the id. + string PrivateEndpointId { get; set; } + /// Represents Private link service connection state. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get; set; } + /// Gets or sets actions required. + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// Gets or sets description. + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// Gets or sets the status. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties Property { get; set; } + /// Gets or sets provisioning state of the private endpoint connection. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.json.cs new file mode 100644 index 00000000000..a4fc7fdc5c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnection.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private endpoint connection. + public partial class PrivateEndpointConnection + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpointConnection(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnection(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionResponseProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.PowerShell.cs new file mode 100644 index 00000000000..b1149d1d1e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a PrivateEndpointConnection list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionListResultTypeConverter))] + public partial class PrivateEndpointConnectionListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionListResult(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)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 PrivateEndpointConnectionListResult(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal)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.RecoveryServicesDataReplication.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 PrivateEndpointConnection list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionListResultTypeConverter))] + public partial interface IPrivateEndpointConnectionListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.TypeConverter.cs new file mode 100644 index 00000000000..2b0895089df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.cs new file mode 100644 index 00000000000..0c80631e505 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PrivateEndpointConnection list operation. + public partial class PrivateEndpointConnectionListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The PrivateEndpointConnection items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PrivateEndpointConnectionListResult() + { + + } + } + /// The response of a PrivateEndpointConnection list operation. + public partial interface IPrivateEndpointConnectionListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnection items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The PrivateEndpointConnection items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a PrivateEndpointConnection list operation. + internal partial interface IPrivateEndpointConnectionListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The PrivateEndpointConnection items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.json.cs new file mode 100644 index 00000000000..d21a07dd1da --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionListResult.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PrivateEndpointConnection list operation. + public partial class PrivateEndpointConnectionListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnection) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnection.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.PowerShell.cs new file mode 100644 index 00000000000..eb4f322d9a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.PowerShell.cs @@ -0,0 +1,308 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents private endpoint connection proxy request. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionProxyTypeConverter))] + public partial class PrivateEndpointConnectionProxy + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionProxy(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionProxy(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionProxy(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Etag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Etag = (string) content.GetValueForProperty("Etag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Etag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint) content.GetValueForProperty("RemotePrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("RemotePrivateEndpointConnectionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointConnectionDetail = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointConnectionDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointConnectionDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetailsTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointId = (string) content.GetValueForProperty("RemotePrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointManualPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointManualPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceProxy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceProxy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxyTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal PrivateEndpointConnectionProxy(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Etag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Etag = (string) content.GetValueForProperty("Etag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).Etag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint) content.GetValueForProperty("RemotePrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("RemotePrivateEndpointConnectionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointConnectionDetail = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointConnectionDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointConnectionDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetailsTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointId = (string) content.GetValueForProperty("RemotePrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointManualPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointManualPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceProxy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceProxy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxyTypeConverter.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.RecoveryServicesDataReplication.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(); + } + } + /// Represents private endpoint connection proxy request. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionProxyTypeConverter))] + public partial interface IPrivateEndpointConnectionProxy + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.TypeConverter.cs new file mode 100644 index 00000000000..e9a3b47007e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionProxyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionProxy.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProxy.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProxy.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.cs new file mode 100644 index 00000000000..9ac5c32355e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private endpoint connection proxy request. + public partial class PrivateEndpointConnectionProxy : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Backing field for property. + private string _etag; + + /// Gets or sets ETag. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Etag { get => this._etag; set => this._etag = value; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for RemotePrivateEndpoint + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyInternal.RemotePrivateEndpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpoint = value ?? null /* model class */; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the private endpoint connection proxy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).ProvisioningState; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointConnectionDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointConnectionDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointConnectionDetail = value ?? null /* arrayOf */; } + + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RemotePrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointId = value ?? null; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointManualPrivateLinkServiceConnection { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointManualPrivateLinkServiceConnection; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointManualPrivateLinkServiceConnection = value ?? null /* arrayOf */; } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceConnection { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointPrivateLinkServiceConnection; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointPrivateLinkServiceConnection = value ?? null /* arrayOf */; } + + /// Gets or sets the list of private link service proxies. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceProxy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointPrivateLinkServiceProxy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)Property).RemotePrivateEndpointPrivateLinkServiceProxy = value ?? null /* arrayOf */; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public PrivateEndpointConnectionProxy() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Represents private endpoint connection proxy request. + public partial interface IPrivateEndpointConnectionProxy : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets ETag. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + string Etag { get; set; } + /// Gets or sets the provisioning state of the private endpoint connection proxy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the private endpoint connection proxy.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + System.Collections.Generic.List RemotePrivateEndpointConnectionDetail { get; set; } + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string RemotePrivateEndpointId { get; set; } + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + System.Collections.Generic.List RemotePrivateEndpointManualPrivateLinkServiceConnection { get; set; } + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceConnection { get; set; } + /// Gets or sets the list of private link service proxies. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceProxy { get; set; } + + } + /// Represents private endpoint connection proxy request. + internal partial interface IPrivateEndpointConnectionProxyInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Gets or sets ETag. + string Etag { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties Property { get; set; } + /// Gets or sets the provisioning state of the private endpoint connection proxy. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// + /// Represent remote private endpoint information for the private endpoint connection proxy. + /// + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint RemotePrivateEndpoint { get; set; } + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + System.Collections.Generic.List RemotePrivateEndpointConnectionDetail { get; set; } + /// Gets or sets private link service proxy id. + string RemotePrivateEndpointId { get; set; } + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + System.Collections.Generic.List RemotePrivateEndpointManualPrivateLinkServiceConnection { get; set; } + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceConnection { get; set; } + /// Gets or sets the list of private link service proxies. + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceProxy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.json.cs new file mode 100644 index 00000000000..351f55960a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxy.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private endpoint connection proxy request. + public partial class PrivateEndpointConnectionProxy + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionProxy(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionProxy(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyProperties.FromJson(__jsonProperties) : _property;} + {_etag = If( json?.PropertyT("etag"), out var __jsonEtag) ? (string)__jsonEtag : (string)_etag;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != (((object)this._etag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._etag.ToString()) : null, "etag" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.PowerShell.cs new file mode 100644 index 00000000000..beade69dbc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a PrivateEndpointConnectionProxy list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionProxyListResultTypeConverter))] + public partial class PrivateEndpointConnectionProxyListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionProxyListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionProxyListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionProxyListResult(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)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 PrivateEndpointConnectionProxyListResult(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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxyTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal)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.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxy list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionProxyListResultTypeConverter))] + public partial interface IPrivateEndpointConnectionProxyListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.TypeConverter.cs new file mode 100644 index 00000000000..9e5ac39d0ca --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionProxyListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionProxyListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProxyListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProxyListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.cs new file mode 100644 index 00000000000..4c721a877cb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PrivateEndpointConnectionProxy list operation. + public partial class PrivateEndpointConnectionProxyListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The PrivateEndpointConnectionProxy items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// + /// Creates an new instance. + /// + public PrivateEndpointConnectionProxyListResult() + { + + } + } + /// The response of a PrivateEndpointConnectionProxy list operation. + public partial interface IPrivateEndpointConnectionProxyListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateEndpointConnectionProxy items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The PrivateEndpointConnectionProxy items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a PrivateEndpointConnectionProxy list operation. + internal partial interface IPrivateEndpointConnectionProxyListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The PrivateEndpointConnectionProxy items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.json.cs new file mode 100644 index 00000000000..f002e594fe0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PrivateEndpointConnectionProxy list operation. + public partial class PrivateEndpointConnectionProxyListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionProxyListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionProxyListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.PowerShell.cs new file mode 100644 index 00000000000..d18ad3dc165 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.PowerShell.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents private endpoint connection proxy request. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionProxyPropertiesTypeConverter))] + public partial class PrivateEndpointConnectionProxyProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionProxyProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionProxyProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionProxyProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RemotePrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint) content.GetValueForProperty("RemotePrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointConnectionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointConnectionDetail = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointConnectionDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointConnectionDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetailsTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointId = (string) content.GetValueForProperty("RemotePrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointManualPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointManualPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceProxy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceProxy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxyTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal PrivateEndpointConnectionProxyProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RemotePrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint) content.GetValueForProperty("RemotePrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointConnectionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointConnectionDetail = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointConnectionDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointConnectionDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetailsTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointId = (string) content.GetValueForProperty("RemotePrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointManualPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointManualPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointManualPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateEndpointPrivateLinkServiceProxy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy = (System.Collections.Generic.List) content.GetValueForProperty("RemotePrivateEndpointPrivateLinkServiceProxy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal)this).RemotePrivateEndpointPrivateLinkServiceProxy, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxyTypeConverter.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.RecoveryServicesDataReplication.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(); + } + } + /// Represents private endpoint connection proxy request. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionProxyPropertiesTypeConverter))] + public partial interface IPrivateEndpointConnectionProxyProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.TypeConverter.cs new file mode 100644 index 00000000000..8e95b007253 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionProxyPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionProxyProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProxyProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionProxyProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.cs new file mode 100644 index 00000000000..2c3342507a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private endpoint connection proxy request. + public partial class PrivateEndpointConnectionProxyProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal + { + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for RemotePrivateEndpoint + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyPropertiesInternal.RemotePrivateEndpoint { get => (this._remotePrivateEndpoint = this._remotePrivateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpoint()); set { {_remotePrivateEndpoint = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the private endpoint connection proxy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint _remotePrivateEndpoint; + + /// + /// Represent remote private endpoint information for the private endpoint connection proxy. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint RemotePrivateEndpoint { get => (this._remotePrivateEndpoint = this._remotePrivateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpoint()); set => this._remotePrivateEndpoint = value; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointConnectionDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).ConnectionDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).ConnectionDetail = value ?? null /* arrayOf */; } + + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RemotePrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).Id = value ?? null; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointManualPrivateLinkServiceConnection { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).ManualPrivateLinkServiceConnection; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).ManualPrivateLinkServiceConnection = value ?? null /* arrayOf */; } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceConnection { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).PrivateLinkServiceConnection; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).PrivateLinkServiceConnection = value ?? null /* arrayOf */; } + + /// Gets or sets the list of private link service proxies. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceProxy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).PrivateLinkServiceProxy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)RemotePrivateEndpoint).PrivateLinkServiceProxy = value ?? null /* arrayOf */; } + + /// + /// Creates an new instance. + /// + public PrivateEndpointConnectionProxyProperties() + { + + } + } + /// Represents private endpoint connection proxy request. + public partial interface IPrivateEndpointConnectionProxyProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the provisioning state of the private endpoint connection proxy. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the private endpoint connection proxy.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + System.Collections.Generic.List RemotePrivateEndpointConnectionDetail { get; set; } + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string RemotePrivateEndpointId { get; set; } + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + System.Collections.Generic.List RemotePrivateEndpointManualPrivateLinkServiceConnection { get; set; } + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceConnection { get; set; } + /// Gets or sets the list of private link service proxies. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceProxy { get; set; } + + } + /// Represents private endpoint connection proxy request. + internal partial interface IPrivateEndpointConnectionProxyPropertiesInternal + + { + /// Gets or sets the provisioning state of the private endpoint connection proxy. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// + /// Represent remote private endpoint information for the private endpoint connection proxy. + /// + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint RemotePrivateEndpoint { get; set; } + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + System.Collections.Generic.List RemotePrivateEndpointConnectionDetail { get; set; } + /// Gets or sets private link service proxy id. + string RemotePrivateEndpointId { get; set; } + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + System.Collections.Generic.List RemotePrivateEndpointManualPrivateLinkServiceConnection { get; set; } + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceConnection { get; set; } + /// Gets or sets the list of private link service proxies. + System.Collections.Generic.List RemotePrivateEndpointPrivateLinkServiceProxy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.json.cs new file mode 100644 index 00000000000..c4ca8d1c6a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionProxyProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private endpoint connection proxy request. + public partial class PrivateEndpointConnectionProxyProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionProxyProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionProxyProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_remotePrivateEndpoint = If( json?.PropertyT("remotePrivateEndpoint"), out var __jsonRemotePrivateEndpoint) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpoint.FromJson(__jsonRemotePrivateEndpoint) : _remotePrivateEndpoint;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._remotePrivateEndpoint ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._remotePrivateEndpoint.ToJson(null,serializationMode) : null, "remotePrivateEndpoint" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.PowerShell.cs new file mode 100644 index 00000000000..382f504f9a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.PowerShell.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents Private endpoint connection response properties. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionResponsePropertiesTypeConverter))] + public partial class PrivateEndpointConnectionResponseProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateEndpointConnectionResponseProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateEndpointConnectionResponseProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a + /// json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateEndpointConnectionResponseProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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 PrivateEndpointConnectionResponseProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrivateEndpoint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpoint = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint) content.GetValueForProperty("PrivateEndpoint",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpoint, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointTypeConverter.ConvertFrom); + } + if (content.Contains("PrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("PrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpointId = (string) content.GetValueForProperty("PrivateEndpointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateEndpointId, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("PrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal)this).PrivateLinkServiceConnectionStateActionsRequired, 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.RecoveryServicesDataReplication.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(); + } + } + /// Represents Private endpoint connection response properties. + [System.ComponentModel.TypeConverter(typeof(PrivateEndpointConnectionResponsePropertiesTypeConverter))] + public partial interface IPrivateEndpointConnectionResponseProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.TypeConverter.cs new file mode 100644 index 00000000000..eb1e50d2aec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateEndpointConnectionResponsePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateEndpointConnectionResponseProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionResponseProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateEndpointConnectionResponseProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.cs new file mode 100644 index 00000000000..51934da0d9f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents Private endpoint connection response properties. + public partial class PrivateEndpointConnectionResponseProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal + { + + /// Internal Acessors for PrivateEndpoint + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal.PrivateEndpoint { get => (this._privateEndpoint = this._privateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpoint()); set { {_privateEndpoint = value;} } } + + /// Internal Acessors for PrivateLinkServiceConnectionState + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal.PrivateLinkServiceConnectionState { get => (this._privateLinkServiceConnectionState = this._privateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionState()); set { {_privateLinkServiceConnectionState = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponsePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint _privateEndpoint; + + /// + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint PrivateEndpoint { get => (this._privateEndpoint = this._privateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpoint()); set => this._privateEndpoint = value; } + + /// Gets or sets the id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal)PrivateEndpoint).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointInternal)PrivateEndpoint).Id = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState _privateLinkServiceConnectionState; + + /// Represents Private link service connection state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get => (this._privateLinkServiceConnectionState = this._privateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionState()); set => this._privateLinkServiceConnectionState = value; } + + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).ActionsRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).ActionsRequired = value ?? null; } + + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Description = value ?? null; } + + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PrivateLinkServiceConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)PrivateLinkServiceConnectionState).Status = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets provisioning state of the private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// + /// Creates an new instance. + /// + public PrivateEndpointConnectionResponseProperties() + { + + } + } + /// Represents Private endpoint connection response properties. + public partial interface IPrivateEndpointConnectionResponseProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointId { get; set; } + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets actions required.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the status.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// Gets or sets provisioning state of the private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets provisioning state of the private endpoint connection.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Represents Private endpoint connection response properties. + internal partial interface IPrivateEndpointConnectionResponsePropertiesInternal + + { + /// + /// Represent private Endpoint network resource that is linked to the Private Endpoint connection. + /// + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpoint PrivateEndpoint { get; set; } + /// Gets or sets the id. + string PrivateEndpointId { get; set; } + /// Represents Private link service connection state. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get; set; } + /// Gets or sets actions required. + string PrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// Gets or sets description. + string PrivateLinkServiceConnectionStateDescription { get; set; } + /// Gets or sets the status. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string PrivateLinkServiceConnectionStateStatus { get; set; } + /// Gets or sets provisioning state of the private endpoint connection. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.json.cs new file mode 100644 index 00000000000..2930762049d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateEndpointConnectionResponseProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents Private endpoint connection response properties. + public partial class PrivateEndpointConnectionResponseProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionResponseProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateEndpointConnectionResponseProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateEndpointConnectionResponseProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_privateEndpoint = If( json?.PropertyT("privateEndpoint"), out var __jsonPrivateEndpoint) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpoint.FromJson(__jsonPrivateEndpoint) : _privateEndpoint;} + {_privateLinkServiceConnectionState = If( json?.PropertyT("privateLinkServiceConnectionState"), out var __jsonPrivateLinkServiceConnectionState) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionState.FromJson(__jsonPrivateLinkServiceConnectionState) : _privateLinkServiceConnectionState;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._privateEndpoint ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._privateEndpoint.ToJson(null,serializationMode) : null, "privateEndpoint" ,container.Add ); + AddIf( null != this._privateLinkServiceConnectionState ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._privateLinkServiceConnectionState.ToJson(null,serializationMode) : null, "privateLinkServiceConnectionState" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.PowerShell.cs new file mode 100644 index 00000000000..c73d748b106 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.PowerShell.cs @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents private link resource. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceTypeConverter))] + public partial class PrivateLinkResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateLinkResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkResource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkResource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkResource(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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourcePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredZoneName, __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 PrivateLinkResource(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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourcePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal)this).RequiredZoneName, __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.RecoveryServicesDataReplication.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(); + } + } + /// Represents private link resource. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceTypeConverter))] + public partial interface IPrivateLinkResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.TypeConverter.cs new file mode 100644 index 00000000000..111a8c2aaff --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateLinkResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkResource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.cs new file mode 100644 index 00000000000..384022655b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.cs @@ -0,0 +1,225 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private link resource. + public partial class PrivateLinkResource : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Gets or sets the group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string GroupId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).GroupId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).GroupId = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the private link resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).ProvisioningState; } + + /// + /// Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable + /// resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RequiredMember { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredMember; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredMember = value ?? null /* arrayOf */; } + + /// Gets or sets the private DNS zone names. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List RequiredZoneName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredZoneName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)Property).RequiredZoneName = value ?? null /* arrayOf */; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public PrivateLinkResource() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Represents private link resource. + public partial interface IPrivateLinkResource : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets the group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the group id.", + SerializedName = @"groupId", + PossibleTypes = new [] { typeof(string) })] + string GroupId { get; set; } + /// Gets or sets the provisioning state of the private link resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the private link resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable + /// resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable resource.", + SerializedName = @"requiredMembers", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredMember { get; set; } + /// Gets or sets the private DNS zone names. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the private DNS zone names.", + SerializedName = @"requiredZoneNames", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredZoneName { get; set; } + + } + /// Represents private link resource. + internal partial interface IPrivateLinkResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Gets or sets the group id. + string GroupId { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties Property { get; set; } + /// Gets or sets the provisioning state of the private link resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// + /// Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable + /// resource. + /// + System.Collections.Generic.List RequiredMember { get; set; } + /// Gets or sets the private DNS zone names. + System.Collections.Generic.List RequiredZoneName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.json.cs new file mode 100644 index 00000000000..3b59ab94b30 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResource.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private link resource. + public partial class PrivateLinkResource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateLinkResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkResource(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.PowerShell.cs new file mode 100644 index 00000000000..78611bdd2fa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a PrivateLinkResource list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceListResultTypeConverter))] + public partial class PrivateLinkResourceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkResourceListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkResourceListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkResourceListResult(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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)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 PrivateLinkResourceListResult(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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal)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.RecoveryServicesDataReplication.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 PrivateLinkResource list operation. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourceListResultTypeConverter))] + public partial interface IPrivateLinkResourceListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.TypeConverter.cs new file mode 100644 index 00000000000..89c8c7cf37c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkResourceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkResourceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkResourceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkResourceListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.cs new file mode 100644 index 00000000000..4b982a0079b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PrivateLinkResource list operation. + public partial class PrivateLinkResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The PrivateLinkResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PrivateLinkResourceListResult() + { + + } + } + /// The response of a PrivateLinkResource list operation. + public partial interface IPrivateLinkResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 PrivateLinkResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The PrivateLinkResource items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResource) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a PrivateLinkResource list operation. + internal partial interface IPrivateLinkResourceListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The PrivateLinkResource items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.json.cs new file mode 100644 index 00000000000..8953da8a7aa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a PrivateLinkResource list operation. + public partial class PrivateLinkResourceListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateLinkResourceListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkResourceListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateLinkResource) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkResource.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.PowerShell.cs new file mode 100644 index 00000000000..26fe024bd6e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents private link resource properties. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourcePropertiesTypeConverter))] + public partial class PrivateLinkResourceProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkResourceProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkResourceProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkResourceProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)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 PrivateLinkResourceProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId = (string) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).GroupId, global::System.Convert.ToString); + } + if (content.Contains("RequiredMember")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember = (System.Collections.Generic.List) content.GetValueForProperty("RequiredMember",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredMember, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequiredZoneName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName = (System.Collections.Generic.List) content.GetValueForProperty("RequiredZoneName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).RequiredZoneName, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal)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.RecoveryServicesDataReplication.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(); + } + } + /// Represents private link resource properties. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkResourcePropertiesTypeConverter))] + public partial interface IPrivateLinkResourceProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.TypeConverter.cs new file mode 100644 index 00000000000..db7a2f705aa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkResourcePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkResourceProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkResourceProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkResourceProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.cs new file mode 100644 index 00000000000..1b714cddf4c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private link resource properties. + public partial class PrivateLinkResourceProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal + { + + /// Backing field for property. + private string _groupId; + + /// Gets or sets the group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string GroupId { get => this._groupId; set => this._groupId = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourcePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the private link resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private System.Collections.Generic.List _requiredMember; + + /// + /// Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable + /// resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List RequiredMember { get => this._requiredMember; set => this._requiredMember = value; } + + /// Backing field for property. + private System.Collections.Generic.List _requiredZoneName; + + /// Gets or sets the private DNS zone names. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List RequiredZoneName { get => this._requiredZoneName; set => this._requiredZoneName = value; } + + /// Creates an new instance. + public PrivateLinkResourceProperties() + { + + } + } + /// Represents private link resource properties. + public partial interface IPrivateLinkResourceProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the group id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the group id.", + SerializedName = @"groupId", + PossibleTypes = new [] { typeof(string) })] + string GroupId { get; set; } + /// Gets or sets the provisioning state of the private link resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the private link resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// + /// Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable + /// resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable resource.", + SerializedName = @"requiredMembers", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredMember { get; set; } + /// Gets or sets the private DNS zone names. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the private DNS zone names.", + SerializedName = @"requiredZoneNames", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List RequiredZoneName { get; set; } + + } + /// Represents private link resource properties. + internal partial interface IPrivateLinkResourcePropertiesInternal + + { + /// Gets or sets the group id. + string GroupId { get; set; } + /// Gets or sets the provisioning state of the private link resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// + /// Gets or sets the required member. This translates to how many Private IPs should be created for each privately linkable + /// resource. + /// + System.Collections.Generic.List RequiredMember { get; set; } + /// Gets or sets the private DNS zone names. + System.Collections.Generic.List RequiredZoneName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.json.cs new file mode 100644 index 00000000000..492668d4d4d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkResourceProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents private link resource properties. + public partial class PrivateLinkResourceProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkResourceProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateLinkResourceProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkResourceProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_groupId = If( json?.PropertyT("groupId"), out var __jsonGroupId) ? (string)__jsonGroupId : (string)_groupId;} + {_requiredMember = If( json?.PropertyT("requiredMembers"), out var __jsonRequiredMembers) ? If( __jsonRequiredMembers as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _requiredMember;} + {_requiredZoneName = If( json?.PropertyT("requiredZoneNames"), out var __jsonRequiredZoneNames) ? If( __jsonRequiredZoneNames as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(string) (__p is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString __o ? (string)(__o.ToString()) : null)) ))() : null : _requiredZoneName;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._groupId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._groupId.ToString()) : null, "groupId" ,container.Add ); + if (null != this._requiredMember) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._requiredMember ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("requiredMembers",__w); + } + if (null != this._requiredZoneName) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._requiredZoneName ) + { + AddIf(null != (((object)__s)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__s.ToString()) : null ,__r.Add); + } + container.Add("requiredZoneNames",__r); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.PowerShell.cs new file mode 100644 index 00000000000..dd2a3163214 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents of an NRP private link service connection. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceConnectionTypeConverter))] + public partial class PrivateLinkServiceConnection + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkServiceConnection(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkServiceConnection(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkServiceConnection(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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequestMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).RequestMessage = (string) content.GetValueForProperty("RequestMessage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).RequestMessage, 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 PrivateLinkServiceConnection(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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("GroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).GroupId = (System.Collections.Generic.List) content.GetValueForProperty("GroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).GroupId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("RequestMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).RequestMessage = (string) content.GetValueForProperty("RequestMessage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal)this).RequestMessage, 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.RecoveryServicesDataReplication.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(); + } + } + /// Represents of an NRP private link service connection. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceConnectionTypeConverter))] + public partial interface IPrivateLinkServiceConnection + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.TypeConverter.cs new file mode 100644 index 00000000000..c6e27ba5734 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkServiceConnectionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkServiceConnection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkServiceConnection.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkServiceConnection.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.cs new file mode 100644 index 00000000000..396d2729e0c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents of an NRP private link service connection. + public partial class PrivateLinkServiceConnection : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _groupId; + + /// Gets or sets group ids. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List GroupId { get => this._groupId; set => this._groupId = value; } + + /// Backing field for property. + private string _name; + + /// Gets or sets private link service connection name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _requestMessage; + + /// Gets or sets the request message for the private link service connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RequestMessage { get => this._requestMessage; set => this._requestMessage = value; } + + /// Creates an new instance. + public PrivateLinkServiceConnection() + { + + } + } + /// Represents of an NRP private link service connection. + public partial interface IPrivateLinkServiceConnection : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets group ids. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets group ids.", + SerializedName = @"groupIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List GroupId { get; set; } + /// Gets or sets private link service connection name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets private link service connection name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// Gets or sets the request message for the private link service connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the request message for the private link service connection.", + SerializedName = @"requestMessage", + PossibleTypes = new [] { typeof(string) })] + string RequestMessage { get; set; } + + } + /// Represents of an NRP private link service connection. + internal partial interface IPrivateLinkServiceConnectionInternal + + { + /// Gets or sets group ids. + System.Collections.Generic.List GroupId { get; set; } + /// Gets or sets private link service connection name. + string Name { get; set; } + /// Gets or sets the request message for the private link service connection. + string RequestMessage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.json.cs new file mode 100644 index 00000000000..892fac4c42e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnection.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents of an NRP private link service connection. + public partial class PrivateLinkServiceConnection + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateLinkServiceConnection(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkServiceConnection(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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;} + {_groupId = If( json?.PropertyT("groupIds"), out var __jsonGroupIds) ? If( __jsonGroupIds as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _groupId;} + {_requestMessage = If( json?.PropertyT("requestMessage"), out var __jsonRequestMessage) ? (string)__jsonRequestMessage : (string)_requestMessage;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + if (null != this._groupId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._groupId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("groupIds",__w); + } + AddIf( null != (((object)this._requestMessage)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._requestMessage.ToString()) : null, "requestMessage" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.PowerShell.cs new file mode 100644 index 00000000000..7c515194ade --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.PowerShell.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents Private link service connection state. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceConnectionStateTypeConverter))] + public partial class PrivateLinkServiceConnectionState + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkServiceConnectionState(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkServiceConnectionState(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkServiceConnectionState(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired = (string) content.GetValueForProperty("ActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired, 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 PrivateLinkServiceConnectionState(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("ActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired = (string) content.GetValueForProperty("ActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)this).ActionsRequired, 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.RecoveryServicesDataReplication.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(); + } + } + /// Represents Private link service connection state. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceConnectionStateTypeConverter))] + public partial interface IPrivateLinkServiceConnectionState + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.TypeConverter.cs new file mode 100644 index 00000000000..f55579a9ab3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkServiceConnectionStateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkServiceConnectionState.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkServiceConnectionState.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkServiceConnectionState.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.cs new file mode 100644 index 00000000000..13192af5eda --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents Private link service connection state. + public partial class PrivateLinkServiceConnectionState : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal + { + + /// Backing field for property. + private string _actionsRequired; + + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ActionsRequired { get => this._actionsRequired; set => this._actionsRequired = value; } + + /// Backing field for property. + private string _description; + + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _status; + + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// Creates an new instance. + public PrivateLinkServiceConnectionState() + { + + } + } + /// Represents Private link service connection state. + public partial interface IPrivateLinkServiceConnectionState : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets actions required.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string ActionsRequired { get; set; } + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the status.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string Status { get; set; } + + } + /// Represents Private link service connection state. + internal partial interface IPrivateLinkServiceConnectionStateInternal + + { + /// Gets or sets actions required. + string ActionsRequired { get; set; } + /// Gets or sets description. + string Description { get; set; } + /// Gets or sets the status. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.json.cs new file mode 100644 index 00000000000..37e9f573e1b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceConnectionState.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents Private link service connection state. + public partial class PrivateLinkServiceConnectionState + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateLinkServiceConnectionState(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkServiceConnectionState(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_actionsRequired = If( json?.PropertyT("actionsRequired"), out var __jsonActionsRequired) ? (string)__jsonActionsRequired : (string)_actionsRequired;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._actionsRequired)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._actionsRequired.ToString()) : null, "actionsRequired" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.PowerShell.cs new file mode 100644 index 00000000000..59ec3c4cc93 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.PowerShell.cs @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represents NRP private link service proxy. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceProxyTypeConverter))] + public partial class PrivateLinkServiceProxy + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PrivateLinkServiceProxy(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PrivateLinkServiceProxy(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PrivateLinkServiceProxy(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RemotePrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("RemotePrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("RemotePrivateEndpointConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection) content.GetValueForProperty("RemotePrivateEndpointConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnection, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointConnectionTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("GroupConnectivityInformation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).GroupConnectivityInformation = (System.Collections.Generic.List) content.GetValueForProperty("GroupConnectivityInformation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).GroupConnectivityInformation, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.GroupConnectivityInformationTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("RemotePrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("RemotePrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("RemotePrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateActionsRequired, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointConnectionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnectionId = (string) content.GetValueForProperty("RemotePrivateEndpointConnectionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnectionId, 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 PrivateLinkServiceProxy(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RemotePrivateLinkServiceConnectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionState = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState) content.GetValueForProperty("RemotePrivateLinkServiceConnectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionState, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionStateTypeConverter.ConvertFrom); + } + if (content.Contains("RemotePrivateEndpointConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection) content.GetValueForProperty("RemotePrivateEndpointConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnection, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointConnectionTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("GroupConnectivityInformation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).GroupConnectivityInformation = (System.Collections.Generic.List) content.GetValueForProperty("GroupConnectivityInformation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).GroupConnectivityInformation, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.GroupConnectivityInformationTypeConverter.ConvertFrom)); + } + if (content.Contains("RemotePrivateLinkServiceConnectionStateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateStatus = (string) content.GetValueForProperty("RemotePrivateLinkServiceConnectionStateStatus",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateStatus, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateLinkServiceConnectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateDescription = (string) content.GetValueForProperty("RemotePrivateLinkServiceConnectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateLinkServiceConnectionStateActionsRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateActionsRequired = (string) content.GetValueForProperty("RemotePrivateLinkServiceConnectionStateActionsRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateLinkServiceConnectionStateActionsRequired, global::System.Convert.ToString); + } + if (content.Contains("RemotePrivateEndpointConnectionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnectionId = (string) content.GetValueForProperty("RemotePrivateEndpointConnectionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal)this).RemotePrivateEndpointConnectionId, 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.RecoveryServicesDataReplication.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(); + } + } + /// Represents NRP private link service proxy. + [System.ComponentModel.TypeConverter(typeof(PrivateLinkServiceProxyTypeConverter))] + public partial interface IPrivateLinkServiceProxy + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.TypeConverter.cs new file mode 100644 index 00000000000..df1588612a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PrivateLinkServiceProxyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PrivateLinkServiceProxy.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PrivateLinkServiceProxy.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PrivateLinkServiceProxy.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.cs new file mode 100644 index 00000000000..28cf934a49e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents NRP private link service proxy. + public partial class PrivateLinkServiceProxy : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _groupConnectivityInformation; + + /// Gets or sets group connectivity information. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List GroupConnectivityInformation { get => this._groupConnectivityInformation; set => this._groupConnectivityInformation = value; } + + /// Backing field for property. + private string _id; + + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Internal Acessors for RemotePrivateEndpointConnection + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal.RemotePrivateEndpointConnection { get => (this._remotePrivateEndpointConnection = this._remotePrivateEndpointConnection ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointConnection()); set { {_remotePrivateEndpointConnection = value;} } } + + /// Internal Acessors for RemotePrivateLinkServiceConnectionState + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxyInternal.RemotePrivateLinkServiceConnectionState { get => (this._remotePrivateLinkServiceConnectionState = this._remotePrivateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionState()); set { {_remotePrivateLinkServiceConnectionState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection _remotePrivateEndpointConnection; + + /// Represent remote private endpoint connection. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection RemotePrivateEndpointConnection { get => (this._remotePrivateEndpointConnection = this._remotePrivateEndpointConnection ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointConnection()); set => this._remotePrivateEndpointConnection = value; } + + /// Gets or sets the remote private endpoint connection id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RemotePrivateEndpointConnectionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal)RemotePrivateEndpointConnection).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal)RemotePrivateEndpointConnection).Id = value ?? null; } + + /// + /// Backing field for property. + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState _remotePrivateLinkServiceConnectionState; + + /// Represents Private link service connection state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState RemotePrivateLinkServiceConnectionState { get => (this._remotePrivateLinkServiceConnectionState = this._remotePrivateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionState()); set => this._remotePrivateLinkServiceConnectionState = value; } + + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RemotePrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)RemotePrivateLinkServiceConnectionState).ActionsRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)RemotePrivateLinkServiceConnectionState).ActionsRequired = value ?? null; } + + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RemotePrivateLinkServiceConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)RemotePrivateLinkServiceConnectionState).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)RemotePrivateLinkServiceConnectionState).Description = value ?? null; } + + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RemotePrivateLinkServiceConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)RemotePrivateLinkServiceConnectionState).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionStateInternal)RemotePrivateLinkServiceConnectionState).Status = value ?? null; } + + /// Creates an new instance. + public PrivateLinkServiceProxy() + { + + } + } + /// Represents NRP private link service proxy. + public partial interface IPrivateLinkServiceProxy : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets group connectivity information. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets group connectivity information.", + SerializedName = @"groupConnectivityInformation", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation) })] + System.Collections.Generic.List GroupConnectivityInformation { get; set; } + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Gets or sets the remote private endpoint connection id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the remote private endpoint connection id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string RemotePrivateEndpointConnectionId { get; set; } + /// Gets or sets actions required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets actions required.", + SerializedName = @"actionsRequired", + PossibleTypes = new [] { typeof(string) })] + string RemotePrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// Gets or sets description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets description.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string RemotePrivateLinkServiceConnectionStateDescription { get; set; } + /// Gets or sets the status. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the status.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string RemotePrivateLinkServiceConnectionStateStatus { get; set; } + + } + /// Represents NRP private link service proxy. + internal partial interface IPrivateLinkServiceProxyInternal + + { + /// Gets or sets group connectivity information. + System.Collections.Generic.List GroupConnectivityInformation { get; set; } + /// Gets or sets private link service proxy id. + string Id { get; set; } + /// Represent remote private endpoint connection. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection RemotePrivateEndpointConnection { get; set; } + /// Gets or sets the remote private endpoint connection id. + string RemotePrivateEndpointConnectionId { get; set; } + /// Represents Private link service connection state. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnectionState RemotePrivateLinkServiceConnectionState { get; set; } + /// Gets or sets actions required. + string RemotePrivateLinkServiceConnectionStateActionsRequired { get; set; } + /// Gets or sets description. + string RemotePrivateLinkServiceConnectionStateDescription { get; set; } + /// Gets or sets the status. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Approved", "Disconnected", "Pending", "Rejected")] + string RemotePrivateLinkServiceConnectionStateStatus { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.json.cs new file mode 100644 index 00000000000..61249614687 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/PrivateLinkServiceProxy.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represents NRP private link service proxy. + public partial class PrivateLinkServiceProxy + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new PrivateLinkServiceProxy(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal PrivateLinkServiceProxy(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_remotePrivateLinkServiceConnectionState = If( json?.PropertyT("remotePrivateLinkServiceConnectionState"), out var __jsonRemotePrivateLinkServiceConnectionState) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionState.FromJson(__jsonRemotePrivateLinkServiceConnectionState) : _remotePrivateLinkServiceConnectionState;} + {_remotePrivateEndpointConnection = If( json?.PropertyT("remotePrivateEndpointConnection"), out var __jsonRemotePrivateEndpointConnection) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RemotePrivateEndpointConnection.FromJson(__jsonRemotePrivateEndpointConnection) : _remotePrivateEndpointConnection;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_groupConnectivityInformation = If( json?.PropertyT("groupConnectivityInformation"), out var __jsonGroupConnectivityInformation) ? If( __jsonGroupConnectivityInformation as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IGroupConnectivityInformation) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.GroupConnectivityInformation.FromJson(__u) )) ))() : null : _groupConnectivityInformation;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._remotePrivateLinkServiceConnectionState ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._remotePrivateLinkServiceConnectionState.ToJson(null,serializationMode) : null, "remotePrivateLinkServiceConnectionState" ,container.Add ); + AddIf( null != this._remotePrivateEndpointConnection ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._remotePrivateEndpointConnection.ToJson(null,serializationMode) : null, "remotePrivateEndpointConnection" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + if (null != this._groupConnectivityInformation) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._groupConnectivityInformation ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("groupConnectivityInformation",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.PowerShell.cs new file mode 100644 index 00000000000..b841f2297fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item dynamic memory config. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemDynamicMemoryConfigTypeConverter))] + public partial class ProtectedItemDynamicMemoryConfig + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemDynamicMemoryConfig(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemDynamicMemoryConfig(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemDynamicMemoryConfig(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MaximumMemoryInMegaByte = (long) content.GetValueForProperty("MaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("MinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MinimumMemoryInMegaByte = (long) content.GetValueForProperty("MinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("TargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).TargetMemoryBufferPercentage = (int) content.GetValueForProperty("TargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).TargetMemoryBufferPercentage, (__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 ProtectedItemDynamicMemoryConfig(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MaximumMemoryInMegaByte = (long) content.GetValueForProperty("MaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("MinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MinimumMemoryInMegaByte = (long) content.GetValueForProperty("MinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).MinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("TargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).TargetMemoryBufferPercentage = (int) content.GetValueForProperty("TargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)this).TargetMemoryBufferPercentage, (__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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item dynamic memory config. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemDynamicMemoryConfigTypeConverter))] + public partial interface IProtectedItemDynamicMemoryConfig + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.TypeConverter.cs new file mode 100644 index 00000000000..1376131b44d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemDynamicMemoryConfigTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemDynamicMemoryConfig.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemDynamicMemoryConfig.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemDynamicMemoryConfig.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.cs new file mode 100644 index 00000000000..22d34e394ae --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item dynamic memory config. + public partial class ProtectedItemDynamicMemoryConfig : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal + { + + /// Backing field for property. + private long _maximumMemoryInMegaByte; + + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long MaximumMemoryInMegaByte { get => this._maximumMemoryInMegaByte; set => this._maximumMemoryInMegaByte = value; } + + /// Backing field for property. + private long _minimumMemoryInMegaByte; + + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long MinimumMemoryInMegaByte { get => this._minimumMemoryInMegaByte; set => this._minimumMemoryInMegaByte = value; } + + /// Backing field for property. + private int _targetMemoryBufferPercentage; + + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int TargetMemoryBufferPercentage { get => this._targetMemoryBufferPercentage; set => this._targetMemoryBufferPercentage = value; } + + /// Creates an new instance. + public ProtectedItemDynamicMemoryConfig() + { + + } + } + /// Protected item dynamic memory config. + public partial interface IProtectedItemDynamicMemoryConfig : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets maximum memory in MB.", + SerializedName = @"maximumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long MaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets minimum memory in MB.", + SerializedName = @"minimumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long MinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets target memory buffer in %.", + SerializedName = @"targetMemoryBufferPercentage", + PossibleTypes = new [] { typeof(int) })] + int TargetMemoryBufferPercentage { get; set; } + + } + /// Protected item dynamic memory config. + internal partial interface IProtectedItemDynamicMemoryConfigInternal + + { + /// Gets or sets maximum memory in MB. + long MaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + long MinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + int TargetMemoryBufferPercentage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.json.cs new file mode 100644 index 00000000000..2afa440605f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemDynamicMemoryConfig.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item dynamic memory config. + public partial class ProtectedItemDynamicMemoryConfig + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemDynamicMemoryConfig(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemDynamicMemoryConfig(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_maximumMemoryInMegaByte = If( json?.PropertyT("maximumMemoryInMegaBytes"), out var __jsonMaximumMemoryInMegaBytes) ? (long)__jsonMaximumMemoryInMegaBytes : _maximumMemoryInMegaByte;} + {_minimumMemoryInMegaByte = If( json?.PropertyT("minimumMemoryInMegaBytes"), out var __jsonMinimumMemoryInMegaBytes) ? (long)__jsonMinimumMemoryInMegaBytes : _minimumMemoryInMegaByte;} + {_targetMemoryBufferPercentage = If( json?.PropertyT("targetMemoryBufferPercentage"), out var __jsonTargetMemoryBufferPercentage) ? (int)__jsonTargetMemoryBufferPercentage : _targetMemoryBufferPercentage;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._maximumMemoryInMegaByte), "maximumMemoryInMegaBytes" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._minimumMemoryInMegaByte), "minimumMemoryInMegaBytes" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._targetMemoryBufferPercentage), "targetMemoryBufferPercentage" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.PowerShell.cs new file mode 100644 index 00000000000..965b8cf24c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.PowerShell.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item job properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemJobPropertiesTypeConverter))] + public partial class ProtectedItemJobProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemJobProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemJobProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemJobProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).ScenarioName = (string) content.GetValueForProperty("ScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).ScenarioName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).EndTime, (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 ProtectedItemJobProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).ScenarioName = (string) content.GetValueForProperty("ScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).ScenarioName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)this).EndTime, (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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item job properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemJobPropertiesTypeConverter))] + public partial interface IProtectedItemJobProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.TypeConverter.cs new file mode 100644 index 00000000000..4815054384c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemJobPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemJobProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemJobProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemJobProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.cs new file mode 100644 index 00000000000..15bef87cd57 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item job properties. + public partial class ProtectedItemJobProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal + { + + /// Backing field for property. + private string _displayName; + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; } + + /// Backing field for property. + private global::System.DateTime? _endTime; + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? EndTime { get => this._endTime; } + + /// Backing field for property. + private string _id; + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.DisplayName { get => this._displayName; set { {_displayName = value;} } } + + /// Internal Acessors for EndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.EndTime { get => this._endTime; set { {_endTime = value;} } } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for ScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.ScenarioName { get => this._scenarioName; set { {_scenarioName = value;} } } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.StartTime { get => this._startTime; set { {_startTime = value;} } } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal.State { get => this._state; set { {_state = value;} } } + + /// Backing field for property. + private string _name; + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _scenarioName; + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ScenarioName { get => this._scenarioName; } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; } + + /// Backing field for property. + private string _state; + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string State { get => this._state; } + + /// Creates an new instance. + public ProtectedItemJobProperties() + { + + } + } + /// Protected item job properties. + public partial interface IProtectedItemJobProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string ScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string State { get; } + + } + /// Protected item job properties. + internal partial interface IProtectedItemJobPropertiesInternal + + { + /// Gets or sets the job friendly display name. + string DisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? EndTime { get; set; } + /// Gets or sets job Id. + string Id { get; set; } + /// Gets or sets job name. + string Name { get; set; } + /// Gets or sets protection scenario name. + string ScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? StartTime { get; set; } + /// Gets or sets job state. + string State { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.json.cs new file mode 100644 index 00000000000..ba06bcebc2c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemJobProperties.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item job properties. + public partial class ProtectedItemJobProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemJobProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemJobProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_scenarioName = If( json?.PropertyT("scenarioName"), out var __jsonScenarioName) ? (string)__jsonScenarioName : (string)_scenarioName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? global::System.DateTime.TryParse((string)__jsonEndTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndTimeValue) ? __jsonEndTimeValue : _endTime : _endTime;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._scenarioName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._scenarioName.ToString()) : null, "scenarioName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._endTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._endTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endTime" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.PowerShell.cs new file mode 100644 index 00000000000..4d095df895a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.PowerShell.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item model. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelTypeConverter))] + public partial class ProtectedItemModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModel(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.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ProtectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionState = (string) content.GetValueForProperty("ProtectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionState, global::System.Convert.ToString); + } + if (content.Contains("ResynchronizationState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResynchronizationState = (string) content.GetValueForProperty("ResynchronizationState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResynchronizationState, global::System.Convert.ToString); + } + if (content.Contains("CurrentJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("CurrentJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedEnableProtectionJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedEnableProtectionJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedPlannedFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedPlannedFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastTestFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastTestFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PolicyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).PolicyName = (string) content.GetValueForProperty("PolicyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).PolicyName, global::System.Convert.ToString); + } + if (content.Contains("ReplicationExtensionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationExtensionName = (string) content.GetValueForProperty("ReplicationExtensionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationExtensionName, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("ProtectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionStateDescription = (string) content.GetValueForProperty("ProtectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverState = (string) content.GetValueForProperty("TestFailoverState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverState, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverStateDescription = (string) content.GetValueForProperty("TestFailoverStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverStateDescription, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectId = (string) content.GetValueForProperty("FabricObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectId, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectName = (string) content.GetValueForProperty("FabricObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectName, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("FabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricId = (string) content.GetValueForProperty("FabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricId = (string) content.GetValueForProperty("TargetFabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricId, global::System.Convert.ToString); + } + if (content.Contains("FabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricAgentId = (string) content.GetValueForProperty("FabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricAgentId = (string) content.GetValueForProperty("TargetFabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("ResyncRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResyncRequired = (bool?) content.GetValueForProperty("ResyncRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResyncRequired, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastSuccessfulPlannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulPlannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulPlannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulPlannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulUnplannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulUnplannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulUnplannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulUnplannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulTestFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulTestFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulTestFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulTestFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AllowedJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).AllowedJob = (System.Collections.Generic.List) content.GetValueForProperty("AllowedJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).AllowedJob, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ReplicationHealth")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationHealth = (string) content.GetValueForProperty("ReplicationHealth",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationHealth, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CurrentJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobScenarioName = (string) content.GetValueForProperty("CurrentJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobId = (string) content.GetValueForProperty("CurrentJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobId, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobName = (string) content.GetValueForProperty("CurrentJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobDisplayName = (string) content.GetValueForProperty("CurrentJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobState = (string) content.GetValueForProperty("CurrentJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobState, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobStartTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CurrentJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobEndTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobScenarioName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobId = (string) content.GetValueForProperty("LastFailedEnableProtectionJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobDisplayName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobState = (string) content.GetValueForProperty("LastFailedEnableProtectionJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobScenarioName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobId = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobDisplayName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobState = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobScenarioName = (string) content.GetValueForProperty("LastTestFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobId = (string) content.GetValueForProperty("LastTestFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobName = (string) content.GetValueForProperty("LastTestFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobDisplayName = (string) content.GetValueForProperty("LastTestFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobState = (string) content.GetValueForProperty("LastTestFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomPropertyInstanceType, 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 ProtectedItemModel(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.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ProtectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionState = (string) content.GetValueForProperty("ProtectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionState, global::System.Convert.ToString); + } + if (content.Contains("ResynchronizationState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResynchronizationState = (string) content.GetValueForProperty("ResynchronizationState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResynchronizationState, global::System.Convert.ToString); + } + if (content.Contains("CurrentJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("CurrentJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedEnableProtectionJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedEnableProtectionJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedPlannedFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedPlannedFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastTestFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastTestFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PolicyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).PolicyName = (string) content.GetValueForProperty("PolicyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).PolicyName, global::System.Convert.ToString); + } + if (content.Contains("ReplicationExtensionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationExtensionName = (string) content.GetValueForProperty("ReplicationExtensionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationExtensionName, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("ProtectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionStateDescription = (string) content.GetValueForProperty("ProtectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ProtectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverState = (string) content.GetValueForProperty("TestFailoverState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverState, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverStateDescription = (string) content.GetValueForProperty("TestFailoverStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TestFailoverStateDescription, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectId = (string) content.GetValueForProperty("FabricObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectId, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectName = (string) content.GetValueForProperty("FabricObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricObjectName, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("FabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricId = (string) content.GetValueForProperty("FabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricId = (string) content.GetValueForProperty("TargetFabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricId, global::System.Convert.ToString); + } + if (content.Contains("FabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricAgentId = (string) content.GetValueForProperty("FabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).FabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricAgentId = (string) content.GetValueForProperty("TargetFabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).TargetFabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("ResyncRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResyncRequired = (bool?) content.GetValueForProperty("ResyncRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ResyncRequired, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastSuccessfulPlannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulPlannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulPlannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulPlannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulUnplannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulUnplannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulUnplannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulUnplannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulTestFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulTestFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulTestFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastSuccessfulTestFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AllowedJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).AllowedJob = (System.Collections.Generic.List) content.GetValueForProperty("AllowedJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).AllowedJob, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ReplicationHealth")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationHealth = (string) content.GetValueForProperty("ReplicationHealth",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).ReplicationHealth, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CurrentJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobScenarioName = (string) content.GetValueForProperty("CurrentJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobId = (string) content.GetValueForProperty("CurrentJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobId, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobName = (string) content.GetValueForProperty("CurrentJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobDisplayName = (string) content.GetValueForProperty("CurrentJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobState = (string) content.GetValueForProperty("CurrentJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobState, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobStartTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CurrentJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobEndTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CurrentJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobScenarioName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobId = (string) content.GetValueForProperty("LastFailedEnableProtectionJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobDisplayName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobState = (string) content.GetValueForProperty("LastFailedEnableProtectionJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedEnableProtectionJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobScenarioName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobId = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobDisplayName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobState = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastFailedPlannedFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobScenarioName = (string) content.GetValueForProperty("LastTestFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobId = (string) content.GetValueForProperty("LastTestFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobName = (string) content.GetValueForProperty("LastTestFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobDisplayName = (string) content.GetValueForProperty("LastTestFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobState = (string) content.GetValueForProperty("LastTestFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).LastTestFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item model. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelTypeConverter))] + public partial interface IProtectedItemModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.TypeConverter.cs new file mode 100644 index 00000000000..9358821ade5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.cs new file mode 100644 index 00000000000..f1096c59777 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.cs @@ -0,0 +1,1233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model. + public partial class ProtectedItemModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Gets or sets the allowed scenarios on the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AllowedJob { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).AllowedJob; } + + /// Gets or sets the protected item correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CorrelationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CorrelationId; } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobDisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? CurrentJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobEndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobId; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobName; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? CurrentJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobStartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobState; } + + /// Protected item model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Gets or sets the fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string FabricAgentId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricAgentId; } + + /// Gets or sets the fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string FabricId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricId; } + + /// Gets or sets the fabric object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string FabricObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricObjectId; } + + /// Gets or sets the fabric object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string FabricObjectName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricObjectName; } + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public System.Collections.Generic.List HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).HealthError; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobDisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedEnableProtectionJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobEndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobId; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobName; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedEnableProtectionJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobStartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobState; } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobDisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedPlannedFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobEndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobId; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobName; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedPlannedFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobStartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobState; } + + /// Gets or sets the Last successful planned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastSuccessfulPlannedFailoverTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulPlannedFailoverTime; } + + /// Gets or sets the Last successful test failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastSuccessfulTestFailoverTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulTestFailoverTime; } + + /// Gets or sets the Last successful unplanned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastSuccessfulUnplannedFailoverTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulUnplannedFailoverTime; } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobDisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastTestFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobEndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobId; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobName; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastTestFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobStartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobState; } + + /// Internal Acessors for AllowedJob + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.AllowedJob { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).AllowedJob; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).AllowedJob = value ?? null /* arrayOf */; } + + /// Internal Acessors for CorrelationId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CorrelationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CorrelationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CorrelationId = value ?? null; } + + /// Internal Acessors for CurrentJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJob { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJob; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJob = value ?? null /* model class */; } + + /// Internal Acessors for CurrentJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobDisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobDisplayName = value ?? null; } + + /// Internal Acessors for CurrentJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobEndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobEndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for CurrentJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobId = value ?? null; } + + /// Internal Acessors for CurrentJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobName = value ?? null; } + + /// Internal Acessors for CurrentJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobScenarioName = value ?? null; } + + /// Internal Acessors for CurrentJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for CurrentJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CurrentJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CurrentJobState = value ?? null; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for FabricAgentId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.FabricAgentId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricAgentId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricAgentId = value ?? null; } + + /// Internal Acessors for FabricId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.FabricId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricId = value ?? null; } + + /// Internal Acessors for FabricObjectId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.FabricObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricObjectId = value ?? null; } + + /// Internal Acessors for FabricObjectName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.FabricObjectName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricObjectName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).FabricObjectName = value ?? null; } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.HealthError { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).HealthError; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).HealthError = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastFailedEnableProtectionJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJob { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJob; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJob = value ?? null /* model class */; } + + /// Internal Acessors for LastFailedEnableProtectionJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobDisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobDisplayName = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobEndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobEndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedEnableProtectionJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobId = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobName = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobScenarioName = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedEnableProtectionJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedEnableProtectionJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedEnableProtectionJobState = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJob { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJob; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJob = value ?? null /* model class */; } + + /// Internal Acessors for LastFailedPlannedFailoverJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobDisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobDisplayName = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobEndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobEndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedPlannedFailoverJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobId = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobName = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobScenarioName = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedPlannedFailoverJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastFailedPlannedFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastFailedPlannedFailoverJobState = value ?? null; } + + /// Internal Acessors for LastSuccessfulPlannedFailoverTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastSuccessfulPlannedFailoverTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulPlannedFailoverTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulPlannedFailoverTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastSuccessfulTestFailoverTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastSuccessfulTestFailoverTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulTestFailoverTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulTestFailoverTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastSuccessfulUnplannedFailoverTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastSuccessfulUnplannedFailoverTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulUnplannedFailoverTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastSuccessfulUnplannedFailoverTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastTestFailoverJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJob { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJob; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJob = value ?? null /* model class */; } + + /// Internal Acessors for LastTestFailoverJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobDisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobDisplayName = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobEndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobEndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastTestFailoverJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobId = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobName = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobScenarioName = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastTestFailoverJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.LastTestFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).LastTestFailoverJobState = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProtectionState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.ProtectionState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProtectionState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProtectionState = value ?? null; } + + /// Internal Acessors for ProtectionStateDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.ProtectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProtectionStateDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProtectionStateDescription = value ?? null; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ReplicationHealth + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.ReplicationHealth { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ReplicationHealth; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ReplicationHealth = value ?? null; } + + /// Internal Acessors for ResyncRequired + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.ResyncRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ResyncRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ResyncRequired = value ?? default(bool); } + + /// Internal Acessors for ResynchronizationState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.ResynchronizationState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ResynchronizationState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ResynchronizationState = value ?? null; } + + /// Internal Acessors for SourceFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.SourceFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).SourceFabricProviderId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).SourceFabricProviderId = value ?? null; } + + /// Internal Acessors for TargetFabricAgentId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.TargetFabricAgentId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricAgentId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricAgentId = value ?? null; } + + /// Internal Acessors for TargetFabricId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.TargetFabricId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricId = value ?? null; } + + /// Internal Acessors for TargetFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.TargetFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricProviderId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricProviderId = value ?? null; } + + /// Internal Acessors for TestFailoverState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.TestFailoverState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TestFailoverState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TestFailoverState = value ?? null; } + + /// Internal Acessors for TestFailoverStateDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelInternal.TestFailoverStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TestFailoverStateDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TestFailoverStateDescription = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Gets or sets the policy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string PolicyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).PolicyName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).PolicyName = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelProperties()); set => this._property = value; } + + /// Gets or sets the protection state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProtectionState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProtectionState; } + + /// Gets or sets the protection state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProtectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProtectionStateDescription; } + + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets or sets the replication extension name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ReplicationExtensionName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ReplicationExtensionName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ReplicationExtensionName = value ?? null; } + + /// Gets or sets protected item replication health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ReplicationHealth { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ReplicationHealth; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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); } + + /// Gets or sets a value indicating whether resynchronization is required or not. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public bool? ResyncRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ResyncRequired; } + + /// Gets or sets the resynchronization state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ResynchronizationState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).ResynchronizationState; } + + /// Gets or sets the source fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SourceFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).SourceFabricProviderId; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// Gets or sets the target fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string TargetFabricAgentId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricAgentId; } + + /// Gets or sets the target fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string TargetFabricId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricId; } + + /// Gets or sets the target fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string TargetFabricProviderId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TargetFabricProviderId; } + + /// Gets or sets the test failover state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string TestFailoverState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TestFailoverState; } + + /// Gets or sets the Test failover state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string TestFailoverStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)Property).TestFailoverStateDescription; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public ProtectedItemModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Protected item model. + public partial interface IProtectedItemModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Gets or sets the allowed scenarios on the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the allowed scenarios on the protected item.", + SerializedName = @"allowedJobs", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AllowedJob { get; } + /// Gets or sets the protected item correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protected item correlation Id.", + SerializedName = @"correlationId", + PossibleTypes = new [] { typeof(string) })] + string CorrelationId { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CurrentJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CurrentJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobState { get; } + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ProtectedItemModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric agent Id.", + SerializedName = @"fabricAgentId", + PossibleTypes = new [] { typeof(string) })] + string FabricAgentId { get; } + /// Gets or sets the fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric Id.", + SerializedName = @"fabricId", + PossibleTypes = new [] { typeof(string) })] + string FabricId { get; } + /// Gets or sets the fabric object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric object Id.", + SerializedName = @"fabricObjectId", + PossibleTypes = new [] { typeof(string) })] + string FabricObjectId { get; } + /// Gets or sets the fabric object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric object name.", + SerializedName = @"fabricObjectName", + PossibleTypes = new [] { typeof(string) })] + string FabricObjectName { get; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedEnableProtectionJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedEnableProtectionJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobState { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedPlannedFailoverJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedPlannedFailoverJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobState { get; } + /// Gets or sets the Last successful planned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Last successful planned failover time.", + SerializedName = @"lastSuccessfulPlannedFailoverTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastSuccessfulPlannedFailoverTime { get; } + /// Gets or sets the Last successful test failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Last successful test failover time.", + SerializedName = @"lastSuccessfulTestFailoverTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastSuccessfulTestFailoverTime { get; } + /// Gets or sets the Last successful unplanned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Last successful unplanned failover time.", + SerializedName = @"lastSuccessfulUnplannedFailoverTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastSuccessfulUnplannedFailoverTime { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastTestFailoverJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastTestFailoverJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobState { get; } + /// Gets or sets the policy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + string PolicyName { get; set; } + /// Gets or sets the protection state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protection state.", + SerializedName = @"protectionState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("UnprotectedStatesBegin", "EnablingProtection", "EnablingFailed", "DisablingProtection", "MarkedForDeletion", "DisablingFailed", "UnprotectedStatesEnd", "InitialReplicationStatesBegin", "InitialReplicationInProgress", "InitialReplicationCompletedOnPrimary", "InitialReplicationCompletedOnRecovery", "InitialReplicationFailed", "InitialReplicationStatesEnd", "ProtectedStatesBegin", "Protected", "ProtectedStatesEnd", "PlannedFailoverTransitionStatesBegin", "PlannedFailoverInitiated", "PlannedFailoverCompleting", "PlannedFailoverCompleted", "PlannedFailoverFailed", "PlannedFailoverCompletionFailed", "PlannedFailoverTransitionStatesEnd", "UnplannedFailoverTransitionStatesBegin", "UnplannedFailoverInitiated", "UnplannedFailoverCompleting", "UnplannedFailoverCompleted", "UnplannedFailoverFailed", "UnplannedFailoverCompletionFailed", "UnplannedFailoverTransitionStatesEnd", "CommitFailoverStatesBegin", "CommitFailoverInProgressOnPrimary", "CommitFailoverInProgressOnRecovery", "CommitFailoverCompleted", "CommitFailoverFailedOnPrimary", "CommitFailoverFailedOnRecovery", "CommitFailoverStatesEnd", "CancelFailoverStatesBegin", "CancelFailoverInProgressOnPrimary", "CancelFailoverInProgressOnRecovery", "CancelFailoverFailedOnPrimary", "CancelFailoverFailedOnRecovery", "CancelFailoverStatesEnd", "ChangeRecoveryPointStatesBegin", "ChangeRecoveryPointInitiated", "ChangeRecoveryPointCompleted", "ChangeRecoveryPointFailed", "ChangeRecoveryPointStatesEnd", "ReprotectStatesBegin", "ReprotectInitiated", "ReprotectFailed", "ReprotectStatesEnd")] + string ProtectionState { get; } + /// Gets or sets the protection state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protection state description.", + SerializedName = @"protectionStateDescription", + PossibleTypes = new [] { typeof(string) })] + string ProtectionStateDescription { get; } + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric agent.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the replication extension name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + string ReplicationExtensionName { get; set; } + /// Gets or sets protected item replication health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protected item replication health.", + SerializedName = @"replicationHealth", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string ReplicationHealth { get; } + /// Gets or sets a value indicating whether resynchronization is required or not. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether resynchronization is required or not.", + SerializedName = @"resyncRequired", + PossibleTypes = new [] { typeof(bool) })] + bool? ResyncRequired { get; } + /// Gets or sets the resynchronization state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resynchronization state.", + SerializedName = @"resynchronizationState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "ResynchronizationInitiated", "ResynchronizationCompleted", "ResynchronizationFailed")] + string ResynchronizationState { get; } + /// Gets or sets the source fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source fabric provider Id.", + SerializedName = @"sourceFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string SourceFabricProviderId { get; } + /// Gets or sets the target fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric agent Id.", + SerializedName = @"targetFabricAgentId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricAgentId { get; } + /// Gets or sets the target fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric Id.", + SerializedName = @"targetFabricId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricId { get; } + /// Gets or sets the target fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric provider Id.", + SerializedName = @"targetFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricProviderId { get; } + /// Gets or sets the test failover state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test failover state.", + SerializedName = @"testFailoverState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "TestFailoverInitiated", "TestFailoverCompleting", "TestFailoverCompleted", "TestFailoverFailed", "TestFailoverCompletionFailed", "TestFailoverCleanupInitiated", "TestFailoverCleanupCompleting", "MarkedForDeletion")] + string TestFailoverState { get; } + /// Gets or sets the Test failover state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Test failover state description.", + SerializedName = @"testFailoverStateDescription", + PossibleTypes = new [] { typeof(string) })] + string TestFailoverStateDescription { get; } + + } + /// Protected item model. + internal partial interface IProtectedItemModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Gets or sets the allowed scenarios on the protected item. + System.Collections.Generic.List AllowedJob { get; set; } + /// Gets or sets the protected item correlation Id. + string CorrelationId { get; set; } + /// Gets or sets the current scenario. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties CurrentJob { get; set; } + /// Gets or sets the job friendly display name. + string CurrentJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? CurrentJobEndTime { get; set; } + /// Gets or sets job Id. + string CurrentJobId { get; set; } + /// Gets or sets job name. + string CurrentJobName { get; set; } + /// Gets or sets protection scenario name. + string CurrentJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? CurrentJobStartTime { get; set; } + /// Gets or sets job state. + string CurrentJobState { get; set; } + /// Protected item model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for ProtectedItemModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric agent Id. + string FabricAgentId { get; set; } + /// Gets or sets the fabric Id. + string FabricId { get; set; } + /// Gets or sets the fabric object Id. + string FabricObjectId { get; set; } + /// Gets or sets the fabric object name. + string FabricObjectName { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets the last failed enabled protection job. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastFailedEnableProtectionJob { get; set; } + /// Gets or sets the job friendly display name. + string LastFailedEnableProtectionJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? LastFailedEnableProtectionJobEndTime { get; set; } + /// Gets or sets job Id. + string LastFailedEnableProtectionJobId { get; set; } + /// Gets or sets job name. + string LastFailedEnableProtectionJobName { get; set; } + /// Gets or sets protection scenario name. + string LastFailedEnableProtectionJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? LastFailedEnableProtectionJobStartTime { get; set; } + /// Gets or sets job state. + string LastFailedEnableProtectionJobState { get; set; } + /// Gets or sets the last failed planned failover job. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastFailedPlannedFailoverJob { get; set; } + /// Gets or sets the job friendly display name. + string LastFailedPlannedFailoverJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? LastFailedPlannedFailoverJobEndTime { get; set; } + /// Gets or sets job Id. + string LastFailedPlannedFailoverJobId { get; set; } + /// Gets or sets job name. + string LastFailedPlannedFailoverJobName { get; set; } + /// Gets or sets protection scenario name. + string LastFailedPlannedFailoverJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? LastFailedPlannedFailoverJobStartTime { get; set; } + /// Gets or sets job state. + string LastFailedPlannedFailoverJobState { get; set; } + /// Gets or sets the Last successful planned failover time. + global::System.DateTime? LastSuccessfulPlannedFailoverTime { get; set; } + /// Gets or sets the Last successful test failover time. + global::System.DateTime? LastSuccessfulTestFailoverTime { get; set; } + /// Gets or sets the Last successful unplanned failover time. + global::System.DateTime? LastSuccessfulUnplannedFailoverTime { get; set; } + /// Gets or sets the last test failover job. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastTestFailoverJob { get; set; } + /// Gets or sets the job friendly display name. + string LastTestFailoverJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? LastTestFailoverJobEndTime { get; set; } + /// Gets or sets job Id. + string LastTestFailoverJobId { get; set; } + /// Gets or sets job name. + string LastTestFailoverJobName { get; set; } + /// Gets or sets protection scenario name. + string LastTestFailoverJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? LastTestFailoverJobStartTime { get; set; } + /// Gets or sets job state. + string LastTestFailoverJobState { get; set; } + /// Gets or sets the policy name. + string PolicyName { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties Property { get; set; } + /// Gets or sets the protection state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("UnprotectedStatesBegin", "EnablingProtection", "EnablingFailed", "DisablingProtection", "MarkedForDeletion", "DisablingFailed", "UnprotectedStatesEnd", "InitialReplicationStatesBegin", "InitialReplicationInProgress", "InitialReplicationCompletedOnPrimary", "InitialReplicationCompletedOnRecovery", "InitialReplicationFailed", "InitialReplicationStatesEnd", "ProtectedStatesBegin", "Protected", "ProtectedStatesEnd", "PlannedFailoverTransitionStatesBegin", "PlannedFailoverInitiated", "PlannedFailoverCompleting", "PlannedFailoverCompleted", "PlannedFailoverFailed", "PlannedFailoverCompletionFailed", "PlannedFailoverTransitionStatesEnd", "UnplannedFailoverTransitionStatesBegin", "UnplannedFailoverInitiated", "UnplannedFailoverCompleting", "UnplannedFailoverCompleted", "UnplannedFailoverFailed", "UnplannedFailoverCompletionFailed", "UnplannedFailoverTransitionStatesEnd", "CommitFailoverStatesBegin", "CommitFailoverInProgressOnPrimary", "CommitFailoverInProgressOnRecovery", "CommitFailoverCompleted", "CommitFailoverFailedOnPrimary", "CommitFailoverFailedOnRecovery", "CommitFailoverStatesEnd", "CancelFailoverStatesBegin", "CancelFailoverInProgressOnPrimary", "CancelFailoverInProgressOnRecovery", "CancelFailoverFailedOnPrimary", "CancelFailoverFailedOnRecovery", "CancelFailoverStatesEnd", "ChangeRecoveryPointStatesBegin", "ChangeRecoveryPointInitiated", "ChangeRecoveryPointCompleted", "ChangeRecoveryPointFailed", "ChangeRecoveryPointStatesEnd", "ReprotectStatesBegin", "ReprotectInitiated", "ReprotectFailed", "ReprotectStatesEnd")] + string ProtectionState { get; set; } + /// Gets or sets the protection state description. + string ProtectionStateDescription { get; set; } + /// Gets or sets the provisioning state of the fabric agent. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the replication extension name. + string ReplicationExtensionName { get; set; } + /// Gets or sets protected item replication health. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string ReplicationHealth { get; set; } + /// Gets or sets a value indicating whether resynchronization is required or not. + bool? ResyncRequired { get; set; } + /// Gets or sets the resynchronization state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "ResynchronizationInitiated", "ResynchronizationCompleted", "ResynchronizationFailed")] + string ResynchronizationState { get; set; } + /// Gets or sets the source fabric provider Id. + string SourceFabricProviderId { get; set; } + /// Gets or sets the target fabric agent Id. + string TargetFabricAgentId { get; set; } + /// Gets or sets the target fabric Id. + string TargetFabricId { get; set; } + /// Gets or sets the target fabric provider Id. + string TargetFabricProviderId { get; set; } + /// Gets or sets the test failover state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "TestFailoverInitiated", "TestFailoverCompleting", "TestFailoverCompleted", "TestFailoverFailed", "TestFailoverCompletionFailed", "TestFailoverCleanupInitiated", "TestFailoverCleanupCompleting", "MarkedForDeletion")] + string TestFailoverState { get; set; } + /// Gets or sets the Test failover state description. + string TestFailoverStateDescription { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.json.cs new file mode 100644 index 00000000000..1499859c21e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model. + public partial class ProtectedItemModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..73346c85ddc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.PowerShell.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelCustomPropertiesTypeConverter))] + public partial class ProtectedItemModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType, 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 ProtectedItemModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelCustomPropertiesTypeConverter))] + public partial interface IProtectedItemModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..ebbe12c614c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.cs new file mode 100644 index 00000000000..df8a0b01a03 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model custom properties. + public partial class ProtectedItemModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public ProtectedItemModelCustomProperties() + { + + } + } + /// Protected item model custom properties. + public partial interface IProtectedItemModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ProtectedItemModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Protected item model custom properties. + internal partial interface IProtectedItemModelCustomPropertiesInternal + + { + /// Discriminator property for ProtectedItemModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.json.cs new file mode 100644 index 00000000000..133c947e3f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomProperties.json.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model custom properties. + public partial class ProtectedItemModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties + /// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the + /// payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHciprotectedItemModelCustomProperties(json); + } + case "VMwareToAzStackHCI": + { + return new VMwareToAzStackHciprotectedItemModelCustomProperties(json); + } + } + return new ProtectedItemModelCustomProperties(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.PowerShell.cs new file mode 100644 index 00000000000..5abf0d07119 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelCustomPropertiesUpdateTypeConverter))] + public partial class ProtectedItemModelCustomPropertiesUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModelCustomPropertiesUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModelCustomPropertiesUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModelCustomPropertiesUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType, 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 ProtectedItemModelCustomPropertiesUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelCustomPropertiesUpdateTypeConverter))] + public partial interface IProtectedItemModelCustomPropertiesUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.TypeConverter.cs new file mode 100644 index 00000000000..ab3926c8b23 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelCustomPropertiesUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModelCustomPropertiesUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModelCustomPropertiesUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModelCustomPropertiesUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.cs new file mode 100644 index 00000000000..2d29e483146 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model custom properties. + public partial class ProtectedItemModelCustomPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// + /// Creates an new instance. + /// + public ProtectedItemModelCustomPropertiesUpdate() + { + + } + } + /// Protected item model custom properties. + public partial interface IProtectedItemModelCustomPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ProtectedItemModelCustomPropertiesUpdate.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Protected item model custom properties. + internal partial interface IProtectedItemModelCustomPropertiesUpdateInternal + + { + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.json.cs new file mode 100644 index 00000000000..224b3b5da92 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelCustomPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model custom properties. + public partial class ProtectedItemModelCustomPropertiesUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate + /// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the + /// payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHciprotectedItemModelCustomPropertiesUpdate(json); + } + case "VMwareToAzStackHCI": + { + return new VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(json); + } + } + return new ProtectedItemModelCustomPropertiesUpdate(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModelCustomPropertiesUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.PowerShell.cs new file mode 100644 index 00000000000..95d275c1ca2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a ProtectedItemModel list operation. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelListResultTypeConverter))] + public partial class ProtectedItemModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModelListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModelListResult(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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)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 ProtectedItemModelListResult(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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal)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.RecoveryServicesDataReplication.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 ProtectedItemModel list operation. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelListResultTypeConverter))] + public partial interface IProtectedItemModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..25dc81211cd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.cs new file mode 100644 index 00000000000..46392418c2a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a ProtectedItemModel list operation. + public partial class ProtectedItemModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The ProtectedItemModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ProtectedItemModelListResult() + { + + } + } + /// The response of a ProtectedItemModel list operation. + public partial interface IProtectedItemModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ProtectedItemModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ProtectedItemModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a ProtectedItemModel list operation. + internal partial interface IProtectedItemModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The ProtectedItemModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.json.cs new file mode 100644 index 00000000000..531588bb5e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a ProtectedItemModel list operation. + public partial class ProtectedItemModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemModelListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.PowerShell.cs new file mode 100644 index 00000000000..79c5a442f98 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.PowerShell.cs @@ -0,0 +1,620 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item model properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelPropertiesTypeConverter))] + public partial class ProtectedItemModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CurrentJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("CurrentJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedEnableProtectionJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedEnableProtectionJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedPlannedFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedPlannedFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastTestFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastTestFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PolicyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).PolicyName = (string) content.GetValueForProperty("PolicyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).PolicyName, global::System.Convert.ToString); + } + if (content.Contains("ReplicationExtensionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationExtensionName = (string) content.GetValueForProperty("ReplicationExtensionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationExtensionName, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ProtectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionState = (string) content.GetValueForProperty("ProtectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionState, global::System.Convert.ToString); + } + if (content.Contains("ProtectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionStateDescription = (string) content.GetValueForProperty("ProtectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverState = (string) content.GetValueForProperty("TestFailoverState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverState, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverStateDescription = (string) content.GetValueForProperty("TestFailoverStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverStateDescription, global::System.Convert.ToString); + } + if (content.Contains("ResynchronizationState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResynchronizationState = (string) content.GetValueForProperty("ResynchronizationState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResynchronizationState, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectId = (string) content.GetValueForProperty("FabricObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectId, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectName = (string) content.GetValueForProperty("FabricObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectName, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("FabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricId = (string) content.GetValueForProperty("FabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricId = (string) content.GetValueForProperty("TargetFabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricId, global::System.Convert.ToString); + } + if (content.Contains("FabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricAgentId = (string) content.GetValueForProperty("FabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricAgentId = (string) content.GetValueForProperty("TargetFabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("ResyncRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResyncRequired = (bool?) content.GetValueForProperty("ResyncRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResyncRequired, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastSuccessfulPlannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulPlannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulPlannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulPlannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulUnplannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulUnplannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulUnplannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulUnplannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulTestFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulTestFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulTestFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulTestFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AllowedJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).AllowedJob = (System.Collections.Generic.List) content.GetValueForProperty("AllowedJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).AllowedJob, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ReplicationHealth")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationHealth = (string) content.GetValueForProperty("ReplicationHealth",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationHealth, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CurrentJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobScenarioName = (string) content.GetValueForProperty("CurrentJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobId = (string) content.GetValueForProperty("CurrentJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobId, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobName = (string) content.GetValueForProperty("CurrentJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobDisplayName = (string) content.GetValueForProperty("CurrentJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobState = (string) content.GetValueForProperty("CurrentJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobState, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobStartTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CurrentJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobEndTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobScenarioName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobId = (string) content.GetValueForProperty("LastFailedEnableProtectionJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobDisplayName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobState = (string) content.GetValueForProperty("LastFailedEnableProtectionJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobScenarioName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobId = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobDisplayName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobState = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobScenarioName = (string) content.GetValueForProperty("LastTestFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobId = (string) content.GetValueForProperty("LastTestFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobName = (string) content.GetValueForProperty("LastTestFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobDisplayName = (string) content.GetValueForProperty("LastTestFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobState = (string) content.GetValueForProperty("LastTestFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomPropertyInstanceType, 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 ProtectedItemModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CurrentJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("CurrentJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedEnableProtectionJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedEnableProtectionJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastFailedPlannedFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastFailedPlannedFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("LastTestFailoverJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJob = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties) content.GetValueForProperty("LastTestFailoverJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJob, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PolicyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).PolicyName = (string) content.GetValueForProperty("PolicyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).PolicyName, global::System.Convert.ToString); + } + if (content.Contains("ReplicationExtensionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationExtensionName = (string) content.GetValueForProperty("ReplicationExtensionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationExtensionName, global::System.Convert.ToString); + } + if (content.Contains("CorrelationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CorrelationId = (string) content.GetValueForProperty("CorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CorrelationId, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ProtectionState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionState = (string) content.GetValueForProperty("ProtectionState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionState, global::System.Convert.ToString); + } + if (content.Contains("ProtectionStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionStateDescription = (string) content.GetValueForProperty("ProtectionStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ProtectionStateDescription, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverState = (string) content.GetValueForProperty("TestFailoverState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverState, global::System.Convert.ToString); + } + if (content.Contains("TestFailoverStateDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverStateDescription = (string) content.GetValueForProperty("TestFailoverStateDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TestFailoverStateDescription, global::System.Convert.ToString); + } + if (content.Contains("ResynchronizationState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResynchronizationState = (string) content.GetValueForProperty("ResynchronizationState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResynchronizationState, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectId = (string) content.GetValueForProperty("FabricObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectId, global::System.Convert.ToString); + } + if (content.Contains("FabricObjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectName = (string) content.GetValueForProperty("FabricObjectName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricObjectName, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).SourceFabricProviderId = (string) content.GetValueForProperty("SourceFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).SourceFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricProviderId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricProviderId = (string) content.GetValueForProperty("TargetFabricProviderId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricProviderId, global::System.Convert.ToString); + } + if (content.Contains("FabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricId = (string) content.GetValueForProperty("FabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricId = (string) content.GetValueForProperty("TargetFabricId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricId, global::System.Convert.ToString); + } + if (content.Contains("FabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricAgentId = (string) content.GetValueForProperty("FabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).FabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricAgentId = (string) content.GetValueForProperty("TargetFabricAgentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).TargetFabricAgentId, global::System.Convert.ToString); + } + if (content.Contains("ResyncRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResyncRequired = (bool?) content.GetValueForProperty("ResyncRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ResyncRequired, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("LastSuccessfulPlannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulPlannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulPlannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulPlannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulUnplannedFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulUnplannedFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulUnplannedFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulUnplannedFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastSuccessfulTestFailoverTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulTestFailoverTime = (global::System.DateTime?) content.GetValueForProperty("LastSuccessfulTestFailoverTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastSuccessfulTestFailoverTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AllowedJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).AllowedJob = (System.Collections.Generic.List) content.GetValueForProperty("AllowedJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).AllowedJob, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ReplicationHealth")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationHealth = (string) content.GetValueForProperty("ReplicationHealth",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).ReplicationHealth, global::System.Convert.ToString); + } + if (content.Contains("HealthError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).HealthError = (System.Collections.Generic.List) content.GetValueForProperty("HealthError",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).HealthError, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CurrentJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobScenarioName = (string) content.GetValueForProperty("CurrentJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobId = (string) content.GetValueForProperty("CurrentJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobId, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobName = (string) content.GetValueForProperty("CurrentJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobDisplayName = (string) content.GetValueForProperty("CurrentJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobState = (string) content.GetValueForProperty("CurrentJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobState, global::System.Convert.ToString); + } + if (content.Contains("CurrentJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobStartTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CurrentJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobEndTime = (global::System.DateTime?) content.GetValueForProperty("CurrentJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CurrentJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobScenarioName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobId = (string) content.GetValueForProperty("LastFailedEnableProtectionJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobDisplayName = (string) content.GetValueForProperty("LastFailedEnableProtectionJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobState = (string) content.GetValueForProperty("LastFailedEnableProtectionJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedEnableProtectionJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedEnableProtectionJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedEnableProtectionJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedEnableProtectionJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobScenarioName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobId = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobDisplayName = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobState = (string) content.GetValueForProperty("LastFailedPlannedFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastFailedPlannedFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastFailedPlannedFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastFailedPlannedFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastFailedPlannedFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobScenarioName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobScenarioName = (string) content.GetValueForProperty("LastTestFailoverJobScenarioName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobScenarioName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobId = (string) content.GetValueForProperty("LastTestFailoverJobId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobId, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobName = (string) content.GetValueForProperty("LastTestFailoverJobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobDisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobDisplayName = (string) content.GetValueForProperty("LastTestFailoverJobDisplayName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobDisplayName, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobState = (string) content.GetValueForProperty("LastTestFailoverJobState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobState, global::System.Convert.ToString); + } + if (content.Contains("LastTestFailoverJobStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobStartTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobStartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTestFailoverJobEndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobEndTime = (global::System.DateTime?) content.GetValueForProperty("LastTestFailoverJobEndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).LastTestFailoverJobEndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item model properties. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelPropertiesTypeConverter))] + public partial interface IProtectedItemModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..5666671f950 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.cs new file mode 100644 index 00000000000..584b58aded6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.cs @@ -0,0 +1,1225 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model properties. + public partial class ProtectedItemModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _allowedJob; + + /// Gets or sets the allowed scenarios on the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List AllowedJob { get => this._allowedJob; } + + /// Backing field for property. + private string _correlationId; + + /// Gets or sets the protected item correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string CorrelationId { get => this._correlationId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties _currentJob; + + /// Gets or sets the current scenario. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties CurrentJob { get => (this._currentJob = this._currentJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).DisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? CurrentJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).EndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).Id; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).Name; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).ScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? CurrentJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).StartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CurrentJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).State; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties _customProperty; + + /// Protected item model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Backing field for property. + private string _fabricAgentId; + + /// Gets or sets the fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricAgentId { get => this._fabricAgentId; } + + /// Backing field for property. + private string _fabricId; + + /// Gets or sets the fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricId { get => this._fabricId; } + + /// Backing field for property. + private string _fabricObjectId; + + /// Gets or sets the fabric object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricObjectId { get => this._fabricObjectId; } + + /// Backing field for property. + private string _fabricObjectName; + + /// Gets or sets the fabric object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricObjectName { get => this._fabricObjectName; } + + /// Backing field for property. + private System.Collections.Generic.List _healthError; + + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List HealthError { get => this._healthError; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties _lastFailedEnableProtectionJob; + + /// Gets or sets the last failed enabled protection job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastFailedEnableProtectionJob { get => (this._lastFailedEnableProtectionJob = this._lastFailedEnableProtectionJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).DisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedEnableProtectionJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).EndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).Id; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).Name; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).ScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedEnableProtectionJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).StartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedEnableProtectionJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).State; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties _lastFailedPlannedFailoverJob; + + /// Gets or sets the last failed planned failover job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastFailedPlannedFailoverJob { get => (this._lastFailedPlannedFailoverJob = this._lastFailedPlannedFailoverJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).DisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedPlannedFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).EndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).Id; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).Name; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).ScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastFailedPlannedFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).StartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastFailedPlannedFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).State; } + + /// Backing field for property. + private global::System.DateTime? _lastSuccessfulPlannedFailoverTime; + + /// Gets or sets the Last successful planned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastSuccessfulPlannedFailoverTime { get => this._lastSuccessfulPlannedFailoverTime; } + + /// Backing field for property. + private global::System.DateTime? _lastSuccessfulTestFailoverTime; + + /// Gets or sets the Last successful test failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastSuccessfulTestFailoverTime { get => this._lastSuccessfulTestFailoverTime; } + + /// Backing field for property. + private global::System.DateTime? _lastSuccessfulUnplannedFailoverTime; + + /// Gets or sets the Last successful unplanned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastSuccessfulUnplannedFailoverTime { get => this._lastSuccessfulUnplannedFailoverTime; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties _lastTestFailoverJob; + + /// Gets or sets the last test failover job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastTestFailoverJob { get => (this._lastTestFailoverJob = this._lastTestFailoverJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); } + + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).DisplayName; } + + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastTestFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).EndTime; } + + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).Id; } + + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).Name; } + + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).ScenarioName; } + + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? LastTestFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).StartTime; } + + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string LastTestFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).State; } + + /// Internal Acessors for AllowedJob + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.AllowedJob { get => this._allowedJob; set { {_allowedJob = value;} } } + + /// Internal Acessors for CorrelationId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CorrelationId { get => this._correlationId; set { {_correlationId = value;} } } + + /// Internal Acessors for CurrentJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJob { get => (this._currentJob = this._currentJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); set { {_currentJob = value;} } } + + /// Internal Acessors for CurrentJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).DisplayName = value ?? null; } + + /// Internal Acessors for CurrentJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).EndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).EndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for CurrentJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).Id = value ?? null; } + + /// Internal Acessors for CurrentJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).Name = value ?? null; } + + /// Internal Acessors for CurrentJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).ScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).ScenarioName = value ?? null; } + + /// Internal Acessors for CurrentJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for CurrentJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CurrentJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)CurrentJob).State = value ?? null; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for FabricAgentId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.FabricAgentId { get => this._fabricAgentId; set { {_fabricAgentId = value;} } } + + /// Internal Acessors for FabricId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.FabricId { get => this._fabricId; set { {_fabricId = value;} } } + + /// Internal Acessors for FabricObjectId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.FabricObjectId { get => this._fabricObjectId; set { {_fabricObjectId = value;} } } + + /// Internal Acessors for FabricObjectName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.FabricObjectName { get => this._fabricObjectName; set { {_fabricObjectName = value;} } } + + /// Internal Acessors for HealthError + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.HealthError { get => this._healthError; set { {_healthError = value;} } } + + /// Internal Acessors for LastFailedEnableProtectionJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJob { get => (this._lastFailedEnableProtectionJob = this._lastFailedEnableProtectionJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); set { {_lastFailedEnableProtectionJob = value;} } } + + /// Internal Acessors for LastFailedEnableProtectionJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).DisplayName = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).EndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).EndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedEnableProtectionJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).Id = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).Name = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).ScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).ScenarioName = value ?? null; } + + /// Internal Acessors for LastFailedEnableProtectionJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedEnableProtectionJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedEnableProtectionJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedEnableProtectionJob).State = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJob { get => (this._lastFailedPlannedFailoverJob = this._lastFailedPlannedFailoverJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); set { {_lastFailedPlannedFailoverJob = value;} } } + + /// Internal Acessors for LastFailedPlannedFailoverJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).DisplayName = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).EndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).EndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedPlannedFailoverJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).Id = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).Name = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).ScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).ScenarioName = value ?? null; } + + /// Internal Acessors for LastFailedPlannedFailoverJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastFailedPlannedFailoverJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastFailedPlannedFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastFailedPlannedFailoverJob).State = value ?? null; } + + /// Internal Acessors for LastSuccessfulPlannedFailoverTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastSuccessfulPlannedFailoverTime { get => this._lastSuccessfulPlannedFailoverTime; set { {_lastSuccessfulPlannedFailoverTime = value;} } } + + /// Internal Acessors for LastSuccessfulTestFailoverTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastSuccessfulTestFailoverTime { get => this._lastSuccessfulTestFailoverTime; set { {_lastSuccessfulTestFailoverTime = value;} } } + + /// Internal Acessors for LastSuccessfulUnplannedFailoverTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastSuccessfulUnplannedFailoverTime { get => this._lastSuccessfulUnplannedFailoverTime; set { {_lastSuccessfulUnplannedFailoverTime = value;} } } + + /// Internal Acessors for LastTestFailoverJob + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJob { get => (this._lastTestFailoverJob = this._lastTestFailoverJob ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties()); set { {_lastTestFailoverJob = value;} } } + + /// Internal Acessors for LastTestFailoverJobDisplayName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobDisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).DisplayName = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobEndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobEndTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).EndTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).EndTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastTestFailoverJobId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).Id = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).Name = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobScenarioName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobScenarioName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).ScenarioName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).ScenarioName = value ?? null; } + + /// Internal Acessors for LastTestFailoverJobStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastTestFailoverJobState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.LastTestFailoverJobState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobPropertiesInternal)LastTestFailoverJob).State = value ?? null; } + + /// Internal Acessors for ProtectionState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.ProtectionState { get => this._protectionState; set { {_protectionState = value;} } } + + /// Internal Acessors for ProtectionStateDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.ProtectionStateDescription { get => this._protectionStateDescription; set { {_protectionStateDescription = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for ReplicationHealth + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.ReplicationHealth { get => this._replicationHealth; set { {_replicationHealth = value;} } } + + /// Internal Acessors for ResyncRequired + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.ResyncRequired { get => this._resyncRequired; set { {_resyncRequired = value;} } } + + /// Internal Acessors for ResynchronizationState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.ResynchronizationState { get => this._resynchronizationState; set { {_resynchronizationState = value;} } } + + /// Internal Acessors for SourceFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.SourceFabricProviderId { get => this._sourceFabricProviderId; set { {_sourceFabricProviderId = value;} } } + + /// Internal Acessors for TargetFabricAgentId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.TargetFabricAgentId { get => this._targetFabricAgentId; set { {_targetFabricAgentId = value;} } } + + /// Internal Acessors for TargetFabricId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.TargetFabricId { get => this._targetFabricId; set { {_targetFabricId = value;} } } + + /// Internal Acessors for TargetFabricProviderId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.TargetFabricProviderId { get => this._targetFabricProviderId; set { {_targetFabricProviderId = value;} } } + + /// Internal Acessors for TestFailoverState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.TestFailoverState { get => this._testFailoverState; set { {_testFailoverState = value;} } } + + /// Internal Acessors for TestFailoverStateDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesInternal.TestFailoverStateDescription { get => this._testFailoverStateDescription; set { {_testFailoverStateDescription = value;} } } + + /// Backing field for property. + private string _policyName; + + /// Gets or sets the policy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PolicyName { get => this._policyName; set => this._policyName = value; } + + /// Backing field for property. + private string _protectionState; + + /// Gets or sets the protection state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProtectionState { get => this._protectionState; } + + /// Backing field for property. + private string _protectionStateDescription; + + /// Gets or sets the protection state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProtectionStateDescription { get => this._protectionStateDescription; } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _replicationExtensionName; + + /// Gets or sets the replication extension name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ReplicationExtensionName { get => this._replicationExtensionName; set => this._replicationExtensionName = value; } + + /// Backing field for property. + private string _replicationHealth; + + /// Gets or sets protected item replication health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ReplicationHealth { get => this._replicationHealth; } + + /// Backing field for property. + private bool? _resyncRequired; + + /// Gets or sets a value indicating whether resynchronization is required or not. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? ResyncRequired { get => this._resyncRequired; } + + /// Backing field for property. + private string _resynchronizationState; + + /// Gets or sets the resynchronization state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResynchronizationState { get => this._resynchronizationState; } + + /// Backing field for property. + private string _sourceFabricProviderId; + + /// Gets or sets the source fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceFabricProviderId { get => this._sourceFabricProviderId; } + + /// Backing field for property. + private string _targetFabricAgentId; + + /// Gets or sets the target fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetFabricAgentId { get => this._targetFabricAgentId; } + + /// Backing field for property. + private string _targetFabricId; + + /// Gets or sets the target fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetFabricId { get => this._targetFabricId; } + + /// Backing field for property. + private string _targetFabricProviderId; + + /// Gets or sets the target fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetFabricProviderId { get => this._targetFabricProviderId; } + + /// Backing field for property. + private string _testFailoverState; + + /// Gets or sets the test failover state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestFailoverState { get => this._testFailoverState; } + + /// Backing field for property. + private string _testFailoverStateDescription; + + /// Gets or sets the Test failover state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestFailoverStateDescription { get => this._testFailoverStateDescription; } + + /// Creates an new instance. + public ProtectedItemModelProperties() + { + + } + } + /// Protected item model properties. + public partial interface IProtectedItemModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the allowed scenarios on the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the allowed scenarios on the protected item.", + SerializedName = @"allowedJobs", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AllowedJob { get; } + /// Gets or sets the protected item correlation Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protected item correlation Id.", + SerializedName = @"correlationId", + PossibleTypes = new [] { typeof(string) })] + string CorrelationId { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CurrentJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CurrentJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string CurrentJobState { get; } + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ProtectedItemModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric agent Id.", + SerializedName = @"fabricAgentId", + PossibleTypes = new [] { typeof(string) })] + string FabricAgentId { get; } + /// Gets or sets the fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric Id.", + SerializedName = @"fabricId", + PossibleTypes = new [] { typeof(string) })] + string FabricId { get; } + /// Gets or sets the fabric object Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric object Id.", + SerializedName = @"fabricObjectId", + PossibleTypes = new [] { typeof(string) })] + string FabricObjectId { get; } + /// Gets or sets the fabric object name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the fabric object name.", + SerializedName = @"fabricObjectName", + PossibleTypes = new [] { typeof(string) })] + string FabricObjectName { get; } + /// Gets or sets the list of health errors. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of health errors.", + SerializedName = @"healthErrors", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IHealthErrorModel) })] + System.Collections.Generic.List HealthError { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedEnableProtectionJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedEnableProtectionJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string LastFailedEnableProtectionJobState { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedPlannedFailoverJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastFailedPlannedFailoverJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string LastFailedPlannedFailoverJobState { get; } + /// Gets or sets the Last successful planned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Last successful planned failover time.", + SerializedName = @"lastSuccessfulPlannedFailoverTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastSuccessfulPlannedFailoverTime { get; } + /// Gets or sets the Last successful test failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Last successful test failover time.", + SerializedName = @"lastSuccessfulTestFailoverTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastSuccessfulTestFailoverTime { get; } + /// Gets or sets the Last successful unplanned failover time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Last successful unplanned failover time.", + SerializedName = @"lastSuccessfulUnplannedFailoverTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastSuccessfulUnplannedFailoverTime { get; } + /// Gets or sets the job friendly display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the job friendly display name.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobDisplayName { get; } + /// Gets or sets end time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets end time of the job.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastTestFailoverJobEndTime { get; } + /// Gets or sets job Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job Id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobId { get; } + /// Gets or sets job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobName { get; } + /// Gets or sets protection scenario name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protection scenario name.", + SerializedName = @"scenarioName", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobScenarioName { get; } + /// Gets or sets start time of the job. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets start time of the job.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastTestFailoverJobStartTime { get; } + /// Gets or sets job state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets job state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string LastTestFailoverJobState { get; } + /// Gets or sets the policy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + string PolicyName { get; set; } + /// Gets or sets the protection state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protection state.", + SerializedName = @"protectionState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("UnprotectedStatesBegin", "EnablingProtection", "EnablingFailed", "DisablingProtection", "MarkedForDeletion", "DisablingFailed", "UnprotectedStatesEnd", "InitialReplicationStatesBegin", "InitialReplicationInProgress", "InitialReplicationCompletedOnPrimary", "InitialReplicationCompletedOnRecovery", "InitialReplicationFailed", "InitialReplicationStatesEnd", "ProtectedStatesBegin", "Protected", "ProtectedStatesEnd", "PlannedFailoverTransitionStatesBegin", "PlannedFailoverInitiated", "PlannedFailoverCompleting", "PlannedFailoverCompleted", "PlannedFailoverFailed", "PlannedFailoverCompletionFailed", "PlannedFailoverTransitionStatesEnd", "UnplannedFailoverTransitionStatesBegin", "UnplannedFailoverInitiated", "UnplannedFailoverCompleting", "UnplannedFailoverCompleted", "UnplannedFailoverFailed", "UnplannedFailoverCompletionFailed", "UnplannedFailoverTransitionStatesEnd", "CommitFailoverStatesBegin", "CommitFailoverInProgressOnPrimary", "CommitFailoverInProgressOnRecovery", "CommitFailoverCompleted", "CommitFailoverFailedOnPrimary", "CommitFailoverFailedOnRecovery", "CommitFailoverStatesEnd", "CancelFailoverStatesBegin", "CancelFailoverInProgressOnPrimary", "CancelFailoverInProgressOnRecovery", "CancelFailoverFailedOnPrimary", "CancelFailoverFailedOnRecovery", "CancelFailoverStatesEnd", "ChangeRecoveryPointStatesBegin", "ChangeRecoveryPointInitiated", "ChangeRecoveryPointCompleted", "ChangeRecoveryPointFailed", "ChangeRecoveryPointStatesEnd", "ReprotectStatesBegin", "ReprotectInitiated", "ReprotectFailed", "ReprotectStatesEnd")] + string ProtectionState { get; } + /// Gets or sets the protection state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protection state description.", + SerializedName = @"protectionStateDescription", + PossibleTypes = new [] { typeof(string) })] + string ProtectionStateDescription { get; } + /// Gets or sets the provisioning state of the fabric agent. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the fabric agent.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the replication extension name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + string ReplicationExtensionName { get; set; } + /// Gets or sets protected item replication health. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets protected item replication health.", + SerializedName = @"replicationHealth", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string ReplicationHealth { get; } + /// Gets or sets a value indicating whether resynchronization is required or not. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether resynchronization is required or not.", + SerializedName = @"resyncRequired", + PossibleTypes = new [] { typeof(bool) })] + bool? ResyncRequired { get; } + /// Gets or sets the resynchronization state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resynchronization state.", + SerializedName = @"resynchronizationState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "ResynchronizationInitiated", "ResynchronizationCompleted", "ResynchronizationFailed")] + string ResynchronizationState { get; } + /// Gets or sets the source fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source fabric provider Id.", + SerializedName = @"sourceFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string SourceFabricProviderId { get; } + /// Gets or sets the target fabric agent Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric agent Id.", + SerializedName = @"targetFabricAgentId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricAgentId { get; } + /// Gets or sets the target fabric Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric Id.", + SerializedName = @"targetFabricId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricId { get; } + /// Gets or sets the target fabric provider Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target fabric provider Id.", + SerializedName = @"targetFabricProviderId", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricProviderId { get; } + /// Gets or sets the test failover state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test failover state.", + SerializedName = @"testFailoverState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "TestFailoverInitiated", "TestFailoverCompleting", "TestFailoverCompleted", "TestFailoverFailed", "TestFailoverCompletionFailed", "TestFailoverCleanupInitiated", "TestFailoverCleanupCompleting", "MarkedForDeletion")] + string TestFailoverState { get; } + /// Gets or sets the Test failover state description. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Test failover state description.", + SerializedName = @"testFailoverStateDescription", + PossibleTypes = new [] { typeof(string) })] + string TestFailoverStateDescription { get; } + + } + /// Protected item model properties. + internal partial interface IProtectedItemModelPropertiesInternal + + { + /// Gets or sets the allowed scenarios on the protected item. + System.Collections.Generic.List AllowedJob { get; set; } + /// Gets or sets the protected item correlation Id. + string CorrelationId { get; set; } + /// Gets or sets the current scenario. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties CurrentJob { get; set; } + /// Gets or sets the job friendly display name. + string CurrentJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? CurrentJobEndTime { get; set; } + /// Gets or sets job Id. + string CurrentJobId { get; set; } + /// Gets or sets job name. + string CurrentJobName { get; set; } + /// Gets or sets protection scenario name. + string CurrentJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? CurrentJobStartTime { get; set; } + /// Gets or sets job state. + string CurrentJobState { get; set; } + /// Protected item model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for ProtectedItemModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the fabric agent Id. + string FabricAgentId { get; set; } + /// Gets or sets the fabric Id. + string FabricId { get; set; } + /// Gets or sets the fabric object Id. + string FabricObjectId { get; set; } + /// Gets or sets the fabric object name. + string FabricObjectName { get; set; } + /// Gets or sets the list of health errors. + System.Collections.Generic.List HealthError { get; set; } + /// Gets or sets the last failed enabled protection job. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastFailedEnableProtectionJob { get; set; } + /// Gets or sets the job friendly display name. + string LastFailedEnableProtectionJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? LastFailedEnableProtectionJobEndTime { get; set; } + /// Gets or sets job Id. + string LastFailedEnableProtectionJobId { get; set; } + /// Gets or sets job name. + string LastFailedEnableProtectionJobName { get; set; } + /// Gets or sets protection scenario name. + string LastFailedEnableProtectionJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? LastFailedEnableProtectionJobStartTime { get; set; } + /// Gets or sets job state. + string LastFailedEnableProtectionJobState { get; set; } + /// Gets or sets the last failed planned failover job. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastFailedPlannedFailoverJob { get; set; } + /// Gets or sets the job friendly display name. + string LastFailedPlannedFailoverJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? LastFailedPlannedFailoverJobEndTime { get; set; } + /// Gets or sets job Id. + string LastFailedPlannedFailoverJobId { get; set; } + /// Gets or sets job name. + string LastFailedPlannedFailoverJobName { get; set; } + /// Gets or sets protection scenario name. + string LastFailedPlannedFailoverJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? LastFailedPlannedFailoverJobStartTime { get; set; } + /// Gets or sets job state. + string LastFailedPlannedFailoverJobState { get; set; } + /// Gets or sets the Last successful planned failover time. + global::System.DateTime? LastSuccessfulPlannedFailoverTime { get; set; } + /// Gets or sets the Last successful test failover time. + global::System.DateTime? LastSuccessfulTestFailoverTime { get; set; } + /// Gets or sets the Last successful unplanned failover time. + global::System.DateTime? LastSuccessfulUnplannedFailoverTime { get; set; } + /// Gets or sets the last test failover job. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemJobProperties LastTestFailoverJob { get; set; } + /// Gets or sets the job friendly display name. + string LastTestFailoverJobDisplayName { get; set; } + /// Gets or sets end time of the job. + global::System.DateTime? LastTestFailoverJobEndTime { get; set; } + /// Gets or sets job Id. + string LastTestFailoverJobId { get; set; } + /// Gets or sets job name. + string LastTestFailoverJobName { get; set; } + /// Gets or sets protection scenario name. + string LastTestFailoverJobScenarioName { get; set; } + /// Gets or sets start time of the job. + global::System.DateTime? LastTestFailoverJobStartTime { get; set; } + /// Gets or sets job state. + string LastTestFailoverJobState { get; set; } + /// Gets or sets the policy name. + string PolicyName { get; set; } + /// Gets or sets the protection state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("UnprotectedStatesBegin", "EnablingProtection", "EnablingFailed", "DisablingProtection", "MarkedForDeletion", "DisablingFailed", "UnprotectedStatesEnd", "InitialReplicationStatesBegin", "InitialReplicationInProgress", "InitialReplicationCompletedOnPrimary", "InitialReplicationCompletedOnRecovery", "InitialReplicationFailed", "InitialReplicationStatesEnd", "ProtectedStatesBegin", "Protected", "ProtectedStatesEnd", "PlannedFailoverTransitionStatesBegin", "PlannedFailoverInitiated", "PlannedFailoverCompleting", "PlannedFailoverCompleted", "PlannedFailoverFailed", "PlannedFailoverCompletionFailed", "PlannedFailoverTransitionStatesEnd", "UnplannedFailoverTransitionStatesBegin", "UnplannedFailoverInitiated", "UnplannedFailoverCompleting", "UnplannedFailoverCompleted", "UnplannedFailoverFailed", "UnplannedFailoverCompletionFailed", "UnplannedFailoverTransitionStatesEnd", "CommitFailoverStatesBegin", "CommitFailoverInProgressOnPrimary", "CommitFailoverInProgressOnRecovery", "CommitFailoverCompleted", "CommitFailoverFailedOnPrimary", "CommitFailoverFailedOnRecovery", "CommitFailoverStatesEnd", "CancelFailoverStatesBegin", "CancelFailoverInProgressOnPrimary", "CancelFailoverInProgressOnRecovery", "CancelFailoverFailedOnPrimary", "CancelFailoverFailedOnRecovery", "CancelFailoverStatesEnd", "ChangeRecoveryPointStatesBegin", "ChangeRecoveryPointInitiated", "ChangeRecoveryPointCompleted", "ChangeRecoveryPointFailed", "ChangeRecoveryPointStatesEnd", "ReprotectStatesBegin", "ReprotectInitiated", "ReprotectFailed", "ReprotectStatesEnd")] + string ProtectionState { get; set; } + /// Gets or sets the protection state description. + string ProtectionStateDescription { get; set; } + /// Gets or sets the provisioning state of the fabric agent. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the replication extension name. + string ReplicationExtensionName { get; set; } + /// Gets or sets protected item replication health. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Normal", "Warning", "Critical")] + string ReplicationHealth { get; set; } + /// Gets or sets a value indicating whether resynchronization is required or not. + bool? ResyncRequired { get; set; } + /// Gets or sets the resynchronization state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "ResynchronizationInitiated", "ResynchronizationCompleted", "ResynchronizationFailed")] + string ResynchronizationState { get; set; } + /// Gets or sets the source fabric provider Id. + string SourceFabricProviderId { get; set; } + /// Gets or sets the target fabric agent Id. + string TargetFabricAgentId { get; set; } + /// Gets or sets the target fabric Id. + string TargetFabricId { get; set; } + /// Gets or sets the target fabric provider Id. + string TargetFabricProviderId { get; set; } + /// Gets or sets the test failover state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "TestFailoverInitiated", "TestFailoverCompleting", "TestFailoverCompleted", "TestFailoverFailed", "TestFailoverCompletionFailed", "TestFailoverCleanupInitiated", "TestFailoverCleanupCompleting", "MarkedForDeletion")] + string TestFailoverState { get; set; } + /// Gets or sets the Test failover state description. + string TestFailoverStateDescription { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.json.cs new file mode 100644 index 00000000000..09488d54d46 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelProperties.json.cs @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model properties. + public partial class ProtectedItemModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_currentJob = If( json?.PropertyT("currentJob"), out var __jsonCurrentJob) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties.FromJson(__jsonCurrentJob) : _currentJob;} + {_lastFailedEnableProtectionJob = If( json?.PropertyT("lastFailedEnableProtectionJob"), out var __jsonLastFailedEnableProtectionJob) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties.FromJson(__jsonLastFailedEnableProtectionJob) : _lastFailedEnableProtectionJob;} + {_lastFailedPlannedFailoverJob = If( json?.PropertyT("lastFailedPlannedFailoverJob"), out var __jsonLastFailedPlannedFailoverJob) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties.FromJson(__jsonLastFailedPlannedFailoverJob) : _lastFailedPlannedFailoverJob;} + {_lastTestFailoverJob = If( json?.PropertyT("lastTestFailoverJob"), out var __jsonLastTestFailoverJob) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemJobProperties.FromJson(__jsonLastTestFailoverJob) : _lastTestFailoverJob;} + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_policyName = If( json?.PropertyT("policyName"), out var __jsonPolicyName) ? (string)__jsonPolicyName : (string)_policyName;} + {_replicationExtensionName = If( json?.PropertyT("replicationExtensionName"), out var __jsonReplicationExtensionName) ? (string)__jsonReplicationExtensionName : (string)_replicationExtensionName;} + {_correlationId = If( json?.PropertyT("correlationId"), out var __jsonCorrelationId) ? (string)__jsonCorrelationId : (string)_correlationId;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_protectionState = If( json?.PropertyT("protectionState"), out var __jsonProtectionState) ? (string)__jsonProtectionState : (string)_protectionState;} + {_protectionStateDescription = If( json?.PropertyT("protectionStateDescription"), out var __jsonProtectionStateDescription) ? (string)__jsonProtectionStateDescription : (string)_protectionStateDescription;} + {_testFailoverState = If( json?.PropertyT("testFailoverState"), out var __jsonTestFailoverState) ? (string)__jsonTestFailoverState : (string)_testFailoverState;} + {_testFailoverStateDescription = If( json?.PropertyT("testFailoverStateDescription"), out var __jsonTestFailoverStateDescription) ? (string)__jsonTestFailoverStateDescription : (string)_testFailoverStateDescription;} + {_resynchronizationState = If( json?.PropertyT("resynchronizationState"), out var __jsonResynchronizationState) ? (string)__jsonResynchronizationState : (string)_resynchronizationState;} + {_fabricObjectId = If( json?.PropertyT("fabricObjectId"), out var __jsonFabricObjectId) ? (string)__jsonFabricObjectId : (string)_fabricObjectId;} + {_fabricObjectName = If( json?.PropertyT("fabricObjectName"), out var __jsonFabricObjectName) ? (string)__jsonFabricObjectName : (string)_fabricObjectName;} + {_sourceFabricProviderId = If( json?.PropertyT("sourceFabricProviderId"), out var __jsonSourceFabricProviderId) ? (string)__jsonSourceFabricProviderId : (string)_sourceFabricProviderId;} + {_targetFabricProviderId = If( json?.PropertyT("targetFabricProviderId"), out var __jsonTargetFabricProviderId) ? (string)__jsonTargetFabricProviderId : (string)_targetFabricProviderId;} + {_fabricId = If( json?.PropertyT("fabricId"), out var __jsonFabricId) ? (string)__jsonFabricId : (string)_fabricId;} + {_targetFabricId = If( json?.PropertyT("targetFabricId"), out var __jsonTargetFabricId) ? (string)__jsonTargetFabricId : (string)_targetFabricId;} + {_fabricAgentId = If( json?.PropertyT("fabricAgentId"), out var __jsonFabricAgentId) ? (string)__jsonFabricAgentId : (string)_fabricAgentId;} + {_targetFabricAgentId = If( json?.PropertyT("targetFabricAgentId"), out var __jsonTargetFabricAgentId) ? (string)__jsonTargetFabricAgentId : (string)_targetFabricAgentId;} + {_resyncRequired = If( json?.PropertyT("resyncRequired"), out var __jsonResyncRequired) ? (bool?)__jsonResyncRequired : _resyncRequired;} + {_lastSuccessfulPlannedFailoverTime = If( json?.PropertyT("lastSuccessfulPlannedFailoverTime"), out var __jsonLastSuccessfulPlannedFailoverTime) ? global::System.DateTime.TryParse((string)__jsonLastSuccessfulPlannedFailoverTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastSuccessfulPlannedFailoverTimeValue) ? __jsonLastSuccessfulPlannedFailoverTimeValue : _lastSuccessfulPlannedFailoverTime : _lastSuccessfulPlannedFailoverTime;} + {_lastSuccessfulUnplannedFailoverTime = If( json?.PropertyT("lastSuccessfulUnplannedFailoverTime"), out var __jsonLastSuccessfulUnplannedFailoverTime) ? global::System.DateTime.TryParse((string)__jsonLastSuccessfulUnplannedFailoverTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastSuccessfulUnplannedFailoverTimeValue) ? __jsonLastSuccessfulUnplannedFailoverTimeValue : _lastSuccessfulUnplannedFailoverTime : _lastSuccessfulUnplannedFailoverTime;} + {_lastSuccessfulTestFailoverTime = If( json?.PropertyT("lastSuccessfulTestFailoverTime"), out var __jsonLastSuccessfulTestFailoverTime) ? global::System.DateTime.TryParse((string)__jsonLastSuccessfulTestFailoverTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastSuccessfulTestFailoverTimeValue) ? __jsonLastSuccessfulTestFailoverTimeValue : _lastSuccessfulTestFailoverTime : _lastSuccessfulTestFailoverTime;} + {_allowedJob = If( json?.PropertyT("allowedJobs"), out var __jsonAllowedJobs) ? If( __jsonAllowedJobs as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _allowedJob;} + {_replicationHealth = If( json?.PropertyT("replicationHealth"), out var __jsonReplicationHealth) ? (string)__jsonReplicationHealth : (string)_replicationHealth;} + {_healthError = If( json?.PropertyT("healthErrors"), out var __jsonHealthErrors) ? If( __jsonHealthErrors as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IHealthErrorModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.HealthErrorModel.FromJson(__p) )) ))() : null : _healthError;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._currentJob ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._currentJob.ToJson(null,serializationMode) : null, "currentJob" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastFailedEnableProtectionJob ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._lastFailedEnableProtectionJob.ToJson(null,serializationMode) : null, "lastFailedEnableProtectionJob" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastFailedPlannedFailoverJob ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._lastFailedPlannedFailoverJob.ToJson(null,serializationMode) : null, "lastFailedPlannedFailoverJob" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastTestFailoverJob ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._lastTestFailoverJob.ToJson(null,serializationMode) : null, "lastTestFailoverJob" ,container.Add ); + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + AddIf( null != (((object)this._policyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._policyName.ToString()) : null, "policyName" ,container.Add ); + AddIf( null != (((object)this._replicationExtensionName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._replicationExtensionName.ToString()) : null, "replicationExtensionName" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._correlationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._correlationId.ToString()) : null, "correlationId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._protectionState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._protectionState.ToString()) : null, "protectionState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._protectionStateDescription)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._protectionStateDescription.ToString()) : null, "protectionStateDescription" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testFailoverState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testFailoverState.ToString()) : null, "testFailoverState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testFailoverStateDescription)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testFailoverStateDescription.ToString()) : null, "testFailoverStateDescription" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resynchronizationState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resynchronizationState.ToString()) : null, "resynchronizationState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricObjectId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricObjectId.ToString()) : null, "fabricObjectId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricObjectName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricObjectName.ToString()) : null, "fabricObjectName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceFabricProviderId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceFabricProviderId.ToString()) : null, "sourceFabricProviderId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetFabricProviderId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetFabricProviderId.ToString()) : null, "targetFabricProviderId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricId.ToString()) : null, "fabricId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetFabricId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetFabricId.ToString()) : null, "targetFabricId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fabricAgentId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricAgentId.ToString()) : null, "fabricAgentId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetFabricAgentId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetFabricAgentId.ToString()) : null, "targetFabricAgentId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resyncRequired ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._resyncRequired) : null, "resyncRequired" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastSuccessfulPlannedFailoverTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastSuccessfulPlannedFailoverTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastSuccessfulPlannedFailoverTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastSuccessfulUnplannedFailoverTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastSuccessfulUnplannedFailoverTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastSuccessfulUnplannedFailoverTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastSuccessfulTestFailoverTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastSuccessfulTestFailoverTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastSuccessfulTestFailoverTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._allowedJob) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._allowedJob ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("allowedJobs",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._replicationHealth)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._replicationHealth.ToString()) : null, "replicationHealth" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._healthError) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._healthError ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("healthErrors",__r); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.PowerShell.cs new file mode 100644 index 00000000000..59bc011586f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item model properties update. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelPropertiesUpdateTypeConverter))] + public partial class ProtectedItemModelPropertiesUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModelPropertiesUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModelPropertiesUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModelPropertiesUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomPropertyInstanceType, 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 ProtectedItemModelPropertiesUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item model properties update. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelPropertiesUpdateTypeConverter))] + public partial interface IProtectedItemModelPropertiesUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.TypeConverter.cs new file mode 100644 index 00000000000..cf82d3d061b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelPropertiesUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModelPropertiesUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModelPropertiesUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModelPropertiesUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.cs new file mode 100644 index 00000000000..011e3256272 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model properties update. + public partial class ProtectedItemModelPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate _customProperty; + + /// Protected item model custom properties update. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate()); set => this._customProperty = value; } + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)CustomProperty).InstanceType = value ?? null; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate()); set { {_customProperty = value;} } } + + /// Creates an new instance. + public ProtectedItemModelPropertiesUpdate() + { + + } + } + /// Protected item model properties update. + public partial interface IProtectedItemModelPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ProtectedItemModelCustomPropertiesUpdate.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + + } + /// Protected item model properties update. + internal partial interface IProtectedItemModelPropertiesUpdateInternal + + { + /// Protected item model custom properties update. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate CustomProperty { get; set; } + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + string CustomPropertyInstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.json.cs new file mode 100644 index 00000000000..26a9a5bed06 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model properties update. + public partial class ProtectedItemModelPropertiesUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemModelPropertiesUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModelPropertiesUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate.FromJson(__jsonCustomProperties) : _customProperty;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.PowerShell.cs new file mode 100644 index 00000000000..47ee7331707 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.PowerShell.cs @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Protected item model update. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelUpdateTypeConverter))] + public partial class ProtectedItemModelUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProtectedItemModelUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProtectedItemModelUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProtectedItemModelUpdate(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.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)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.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)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("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomPropertyInstanceType, 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 ProtectedItemModelUpdate(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.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)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.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)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("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Protected item model update. + [System.ComponentModel.TypeConverter(typeof(ProtectedItemModelUpdateTypeConverter))] + public partial interface IProtectedItemModelUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.TypeConverter.cs new file mode 100644 index 00000000000..0009da63444 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProtectedItemModelUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProtectedItemModelUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProtectedItemModelUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProtectedItemModelUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.cs new file mode 100644 index 00000000000..b2761d71913 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model update. + public partial class ProtectedItemModelUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal + { + + /// Protected item model custom properties update. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// Backing field for property. + private string _id; + + /// Gets or sets the Id of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdateInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesUpdate()); set { {_property = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdateInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Gets or sets the name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate _property; + + /// Protected item model properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesUpdate()); set => this._property = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData _systemData; + + /// Metadata pertaining to creation and last modification of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ProtectedItemModelUpdate() + { + + } + } + /// Protected item model update. + public partial interface IProtectedItemModelUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ProtectedItemModelCustomPropertiesUpdate.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the Id of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Id of the resource.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Gets or sets the name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the name of the resource.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// Gets or sets the type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the type of the resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Protected item model update. + internal partial interface IProtectedItemModelUpdateInternal + + { + /// Protected item model custom properties update. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate CustomProperty { get; set; } + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the Id of the resource. + string Id { get; set; } + /// Gets or sets the name of the resource. + string Name { get; set; } + /// Protected item model properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelPropertiesUpdate Property { get; set; } + /// Metadata pertaining to creation and last modification of the resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// Gets or sets the type of the resource. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.json.cs new file mode 100644 index 00000000000..fc88f0410fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProtectedItemModelUpdate.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Protected item model update. + public partial class ProtectedItemModelUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProtectedItemModelUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProtectedItemModelUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ProtectedItemModelPropertiesUpdate.FromJson(__jsonProperties) : _property;} + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs new file mode 100644 index 00000000000..d847c5fe047 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs new file mode 100644 index 00000000000..548f6924280 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.cs new file mode 100644 index 00000000000..73b127ea15a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ProxyResource.json.cs new file mode 100644 index 00000000000..37b89b5c893 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.PowerShell.cs new file mode 100644 index 00000000000..27af07b1d57 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.PowerShell.cs @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Recovery point model. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelTypeConverter))] + public partial class RecoveryPointModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRecoveryPointModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RecoveryPointModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RecoveryPointModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RecoveryPointModel(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.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("RecoveryPointTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointTime = (global::System.DateTime?) content.GetValueForProperty("RecoveryPointTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RecoveryPointType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointType = (string) content.GetValueForProperty("RecoveryPointType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointType, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomPropertyInstanceType, 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 RecoveryPointModel(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.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("RecoveryPointTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointTime = (global::System.DateTime?) content.GetValueForProperty("RecoveryPointTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RecoveryPointType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointType = (string) content.GetValueForProperty("RecoveryPointType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).RecoveryPointType, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Recovery point model. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelTypeConverter))] + public partial interface IRecoveryPointModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.TypeConverter.cs new file mode 100644 index 00000000000..eae6e4bed91 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RecoveryPointModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRecoveryPointModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RecoveryPointModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RecoveryPointModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RecoveryPointModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.cs new file mode 100644 index 00000000000..c6d59c05cb3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Recovery point model. + public partial class RecoveryPointModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Recovery point model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the recovery point item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets or sets the recovery point time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? RecoveryPointTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).RecoveryPointTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).RecoveryPointTime = value ?? default(global::System.DateTime); } + + /// Gets or sets the recovery point type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string RecoveryPointType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).RecoveryPointType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)Property).RecoveryPointType = value ?? null; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public RecoveryPointModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Recovery point model. + public partial interface IRecoveryPointModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for RecoveryPointModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the recovery point item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the recovery point item.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the recovery point time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the recovery point time.", + SerializedName = @"recoveryPointTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? RecoveryPointTime { get; set; } + /// Gets or sets the recovery point type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the recovery point type.", + SerializedName = @"recoveryPointType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("ApplicationConsistent", "CrashConsistent")] + string RecoveryPointType { get; set; } + + } + /// Recovery point model. + internal partial interface IRecoveryPointModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Recovery point model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for RecoveryPointModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the recovery point item. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the recovery point time. + global::System.DateTime? RecoveryPointTime { get; set; } + /// Gets or sets the recovery point type. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("ApplicationConsistent", "CrashConsistent")] + string RecoveryPointType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.json.cs new file mode 100644 index 00000000000..83963de862e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Recovery point model. + public partial class RecoveryPointModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new RecoveryPointModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RecoveryPointModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..1fbdb0db0f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.PowerShell.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Recovery point model custom properties. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelCustomPropertiesTypeConverter))] + public partial class RecoveryPointModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RecoveryPointModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RecoveryPointModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RecoveryPointModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType, 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 RecoveryPointModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Recovery point model custom properties. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelCustomPropertiesTypeConverter))] + public partial interface IRecoveryPointModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..f59e8eb921b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RecoveryPointModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RecoveryPointModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RecoveryPointModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RecoveryPointModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.cs new file mode 100644 index 00000000000..d7b24549c47 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Recovery point model custom properties. + public partial class RecoveryPointModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public RecoveryPointModelCustomProperties() + { + + } + } + /// Recovery point model custom properties. + public partial interface IRecoveryPointModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for RecoveryPointModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Recovery point model custom properties. + internal partial interface IRecoveryPointModelCustomPropertiesInternal + + { + /// Discriminator property for RecoveryPointModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.json.cs new file mode 100644 index 00000000000..b1c96cbf13f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelCustomProperties.json.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Recovery point model custom properties. + public partial class RecoveryPointModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties + /// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the + /// payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHcirecoveryPointModelCustomProperties(json); + } + case "VMwareToAzStackHCIRecoveryPointModelCustomProperties": + { + return new VMwareToAzStackHcirecoveryPointModelCustomProperties(json); + } + } + return new RecoveryPointModelCustomProperties(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RecoveryPointModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.PowerShell.cs new file mode 100644 index 00000000000..3a45c920a03 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a RecoveryPointModel list operation. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelListResultTypeConverter))] + public partial class RecoveryPointModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RecoveryPointModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RecoveryPointModelListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RecoveryPointModelListResult(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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)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 RecoveryPointModelListResult(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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal)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.RecoveryServicesDataReplication.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 RecoveryPointModel list operation. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelListResultTypeConverter))] + public partial interface IRecoveryPointModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..de4d7c775d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RecoveryPointModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RecoveryPointModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RecoveryPointModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RecoveryPointModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.cs new file mode 100644 index 00000000000..34f46b4500c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a RecoveryPointModel list operation. + public partial class RecoveryPointModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The RecoveryPointModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public RecoveryPointModelListResult() + { + + } + } + /// The response of a RecoveryPointModel list operation. + public partial interface IRecoveryPointModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 RecoveryPointModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The RecoveryPointModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a RecoveryPointModel list operation. + internal partial interface IRecoveryPointModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The RecoveryPointModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.json.cs new file mode 100644 index 00000000000..697dd6aa1ca --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a RecoveryPointModel list operation. + public partial class RecoveryPointModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new RecoveryPointModelListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RecoveryPointModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModel.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.PowerShell.cs new file mode 100644 index 00000000000..90257393613 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.PowerShell.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Recovery point model properties. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelPropertiesTypeConverter))] + public partial class RecoveryPointModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RecoveryPointModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RecoveryPointModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RecoveryPointModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("RecoveryPointTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointTime = (global::System.DateTime) content.GetValueForProperty("RecoveryPointTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RecoveryPointType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointType = (string) content.GetValueForProperty("RecoveryPointType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointType, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomPropertyInstanceType, 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 RecoveryPointModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("RecoveryPointTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointTime = (global::System.DateTime) content.GetValueForProperty("RecoveryPointTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RecoveryPointType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointType = (string) content.GetValueForProperty("RecoveryPointType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).RecoveryPointType, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Recovery point model properties. + [System.ComponentModel.TypeConverter(typeof(RecoveryPointModelPropertiesTypeConverter))] + public partial interface IRecoveryPointModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..049e31966a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RecoveryPointModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RecoveryPointModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RecoveryPointModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RecoveryPointModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.cs new file mode 100644 index 00000000000..a3a21ee72b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Recovery point model properties. + public partial class RecoveryPointModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties _customProperty; + + /// Recovery point model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the recovery point item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private global::System.DateTime _recoveryPointTime; + + /// Gets or sets the recovery point time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime RecoveryPointTime { get => this._recoveryPointTime; set => this._recoveryPointTime = value; } + + /// Backing field for property. + private string _recoveryPointType; + + /// Gets or sets the recovery point type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RecoveryPointType { get => this._recoveryPointType; set => this._recoveryPointType = value; } + + /// Creates an new instance. + public RecoveryPointModelProperties() + { + + } + } + /// Recovery point model properties. + public partial interface IRecoveryPointModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for RecoveryPointModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the recovery point item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the recovery point item.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the recovery point time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the recovery point time.", + SerializedName = @"recoveryPointTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime RecoveryPointTime { get; set; } + /// Gets or sets the recovery point type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the recovery point type.", + SerializedName = @"recoveryPointType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("ApplicationConsistent", "CrashConsistent")] + string RecoveryPointType { get; set; } + + } + /// Recovery point model properties. + internal partial interface IRecoveryPointModelPropertiesInternal + + { + /// Recovery point model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for RecoveryPointModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the recovery point item. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the recovery point time. + global::System.DateTime RecoveryPointTime { get; set; } + /// Gets or sets the recovery point type. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("ApplicationConsistent", "CrashConsistent")] + string RecoveryPointType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.json.cs new file mode 100644 index 00000000000..8ce16d7ac26 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryPointModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Recovery point model properties. + public partial class RecoveryPointModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new RecoveryPointModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RecoveryPointModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_recoveryPointTime = If( json?.PropertyT("recoveryPointTime"), out var __jsonRecoveryPointTime) ? global::System.DateTime.TryParse((string)__jsonRecoveryPointTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonRecoveryPointTimeValue) ? __jsonRecoveryPointTimeValue : _recoveryPointTime : _recoveryPointTime;} + {_recoveryPointType = If( json?.PropertyT("recoveryPointType"), out var __jsonRecoveryPointType) ? (string)__jsonRecoveryPointType : (string)_recoveryPointType;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recoveryPointTime.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)), "recoveryPointTime" ,container.Add ); + AddIf( null != (((object)this._recoveryPointType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recoveryPointType.ToString()) : null, "recoveryPointType" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.PowerShell.cs new file mode 100644 index 00000000000..6aefc334a17 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.PowerShell.cs @@ -0,0 +1,309 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(RecoveryServicesDataReplicationIdentityTypeConverter))] + public partial class RecoveryServicesDataReplicationIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RecoveryServicesDataReplicationIdentity(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RecoveryServicesDataReplicationIdentity(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RecoveryServicesDataReplicationIdentity(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.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("VaultName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).VaultName = (string) content.GetValueForProperty("VaultName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).VaultName, global::System.Convert.ToString); + } + if (content.Contains("EmailConfigurationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EmailConfigurationName = (string) content.GetValueForProperty("EmailConfigurationName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EmailConfigurationName, global::System.Convert.ToString); + } + if (content.Contains("EventName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EventName = (string) content.GetValueForProperty("EventName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EventName, global::System.Convert.ToString); + } + if (content.Contains("FabricName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricName = (string) content.GetValueForProperty("FabricName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricName, global::System.Convert.ToString); + } + if (content.Contains("FabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricAgentName = (string) content.GetValueForProperty("FabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("JobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).JobName = (string) content.GetValueForProperty("JobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).JobName, global::System.Convert.ToString); + } + if (content.Contains("PolicyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PolicyName = (string) content.GetValueForProperty("PolicyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PolicyName, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointConnectionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionName = (string) content.GetValueForProperty("PrivateEndpointConnectionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionName, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointConnectionProxyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionProxyName = (string) content.GetValueForProperty("PrivateEndpointConnectionProxyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionProxyName, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateLinkResourceName = (string) content.GetValueForProperty("PrivateLinkResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateLinkResourceName, global::System.Convert.ToString); + } + if (content.Contains("ProtectedItemName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ProtectedItemName = (string) content.GetValueForProperty("ProtectedItemName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ProtectedItemName, global::System.Convert.ToString); + } + if (content.Contains("RecoveryPointName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).RecoveryPointName = (string) content.GetValueForProperty("RecoveryPointName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).RecoveryPointName, global::System.Convert.ToString); + } + if (content.Contains("ReplicationExtensionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ReplicationExtensionName = (string) content.GetValueForProperty("ReplicationExtensionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ReplicationExtensionName, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("DeploymentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).DeploymentId = (string) content.GetValueForProperty("DeploymentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).DeploymentId, global::System.Convert.ToString); + } + if (content.Contains("OperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).OperationId = (string) content.GetValueForProperty("OperationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).OperationId, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)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 RecoveryServicesDataReplicationIdentity(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.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("VaultName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).VaultName = (string) content.GetValueForProperty("VaultName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).VaultName, global::System.Convert.ToString); + } + if (content.Contains("EmailConfigurationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EmailConfigurationName = (string) content.GetValueForProperty("EmailConfigurationName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EmailConfigurationName, global::System.Convert.ToString); + } + if (content.Contains("EventName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EventName = (string) content.GetValueForProperty("EventName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).EventName, global::System.Convert.ToString); + } + if (content.Contains("FabricName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricName = (string) content.GetValueForProperty("FabricName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricName, global::System.Convert.ToString); + } + if (content.Contains("FabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricAgentName = (string) content.GetValueForProperty("FabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).FabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("JobName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).JobName = (string) content.GetValueForProperty("JobName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).JobName, global::System.Convert.ToString); + } + if (content.Contains("PolicyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PolicyName = (string) content.GetValueForProperty("PolicyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PolicyName, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointConnectionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionName = (string) content.GetValueForProperty("PrivateEndpointConnectionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionName, global::System.Convert.ToString); + } + if (content.Contains("PrivateEndpointConnectionProxyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionProxyName = (string) content.GetValueForProperty("PrivateEndpointConnectionProxyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateEndpointConnectionProxyName, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkResourceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateLinkResourceName = (string) content.GetValueForProperty("PrivateLinkResourceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).PrivateLinkResourceName, global::System.Convert.ToString); + } + if (content.Contains("ProtectedItemName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ProtectedItemName = (string) content.GetValueForProperty("ProtectedItemName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ProtectedItemName, global::System.Convert.ToString); + } + if (content.Contains("RecoveryPointName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).RecoveryPointName = (string) content.GetValueForProperty("RecoveryPointName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).RecoveryPointName, global::System.Convert.ToString); + } + if (content.Contains("ReplicationExtensionName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ReplicationExtensionName = (string) content.GetValueForProperty("ReplicationExtensionName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).ReplicationExtensionName, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("DeploymentId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).DeploymentId = (string) content.GetValueForProperty("DeploymentId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).DeploymentId, global::System.Convert.ToString); + } + if (content.Contains("OperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).OperationId = (string) content.GetValueForProperty("OperationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).OperationId, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal)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.RecoveryServicesDataReplication.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(RecoveryServicesDataReplicationIdentityTypeConverter))] + public partial interface IRecoveryServicesDataReplicationIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.TypeConverter.cs new file mode 100644 index 00000000000..b8cfcd34e98 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.TypeConverter.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RecoveryServicesDataReplicationIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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 RecoveryServicesDataReplicationIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RecoveryServicesDataReplicationIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RecoveryServicesDataReplicationIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RecoveryServicesDataReplicationIdentity.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.cs new file mode 100644 index 00000000000..d5588558630 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.cs @@ -0,0 +1,409 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + public partial class RecoveryServicesDataReplicationIdentity : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentityInternal + { + + /// Backing field for property. + private string _deploymentId; + + /// Deployment Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DeploymentId { get => this._deploymentId; set => this._deploymentId = value; } + + /// Backing field for property. + private string _emailConfigurationName; + + /// The email configuration name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EmailConfigurationName { get => this._emailConfigurationName; set => this._emailConfigurationName = value; } + + /// Backing field for property. + private string _eventName; + + /// The event name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EventName { get => this._eventName; set => this._eventName = value; } + + /// Backing field for property. + private string _fabricAgentName; + + /// The fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricAgentName { get => this._fabricAgentName; set => this._fabricAgentName = value; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _jobName; + + /// The job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string JobName { get => this._jobName; set => this._jobName = value; } + + /// Backing field for property. + private string _location; + + /// The name of the Azure region. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private string _operationId; + + /// The ID of an ongoing async operation. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OperationId { get => this._operationId; set => this._operationId = value; } + + /// Backing field for property. + private string _policyName; + + /// The policy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PolicyName { get => this._policyName; set => this._policyName = value; } + + /// Backing field for property. + private string _privateEndpointConnectionName; + + /// The private endpoint connection name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PrivateEndpointConnectionName { get => this._privateEndpointConnectionName; set => this._privateEndpointConnectionName = value; } + + /// Backing field for property. + private string _privateEndpointConnectionProxyName; + + /// The private endpoint connection proxy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PrivateEndpointConnectionProxyName { get => this._privateEndpointConnectionProxyName; set => this._privateEndpointConnectionProxyName = value; } + + /// Backing field for property. + private string _privateLinkResourceName; + + /// The private link name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PrivateLinkResourceName { get => this._privateLinkResourceName; set => this._privateLinkResourceName = value; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = value; } + + /// Backing field for property. + private string _recoveryPointName; + + /// The recovery point name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RecoveryPointName { get => this._recoveryPointName; set => this._recoveryPointName = value; } + + /// Backing field for property. + private string _replicationExtensionName; + + /// The replication extension name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ReplicationExtensionName { get => this._replicationExtensionName; set => this._replicationExtensionName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// Creates an new instance. + public RecoveryServicesDataReplicationIdentity() + { + + } + } + public partial interface IRecoveryServicesDataReplicationIdentity : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Deployment Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Deployment Id.", + SerializedName = @"deploymentId", + PossibleTypes = new [] { typeof(string) })] + string DeploymentId { get; set; } + /// The email configuration name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + string EmailConfigurationName { get; set; } + /// The event name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The event name.", + SerializedName = @"eventName", + PossibleTypes = new [] { typeof(string) })] + string EventName { get; set; } + /// The fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + string FabricAgentName { get; set; } + /// The fabric name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + string FabricName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 job name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The job name.", + SerializedName = @"jobName", + PossibleTypes = new [] { typeof(string) })] + string JobName { get; set; } + /// The name of the Azure region. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The ID of an ongoing async operation. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ID of an ongoing async operation.", + SerializedName = @"operationId", + PossibleTypes = new [] { typeof(string) })] + string OperationId { get; set; } + /// The policy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + string PolicyName { get; set; } + /// The private endpoint connection name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private endpoint connection name.", + SerializedName = @"privateEndpointConnectionName", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointConnectionName { get; set; } + /// The private endpoint connection proxy name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + string PrivateEndpointConnectionProxyName { get; set; } + /// The private link name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The private link name.", + SerializedName = @"privateLinkResourceName", + PossibleTypes = new [] { typeof(string) })] + string PrivateLinkResourceName { get; set; } + /// The protected item name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + string ProtectedItemName { get; set; } + /// The recovery point name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The recovery point name.", + SerializedName = @"recoveryPointName", + PossibleTypes = new [] { typeof(string) })] + string RecoveryPointName { get; set; } + /// The replication extension name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + string ReplicationExtensionName { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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; } + /// The vault name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + string VaultName { get; set; } + + } + internal partial interface IRecoveryServicesDataReplicationIdentityInternal + + { + /// Deployment Id. + string DeploymentId { get; set; } + /// The email configuration name. + string EmailConfigurationName { get; set; } + /// The event name. + string EventName { get; set; } + /// The fabric agent name. + string FabricAgentName { get; set; } + /// The fabric name. + string FabricName { get; set; } + /// Resource identity path + string Id { get; set; } + /// The job name. + string JobName { get; set; } + /// The name of the Azure region. + string Location { get; set; } + /// The ID of an ongoing async operation. + string OperationId { get; set; } + /// The policy name. + string PolicyName { get; set; } + /// The private endpoint connection name. + string PrivateEndpointConnectionName { get; set; } + /// The private endpoint connection proxy name. + string PrivateEndpointConnectionProxyName { get; set; } + /// The private link name. + string PrivateLinkResourceName { get; set; } + /// The protected item name. + string ProtectedItemName { get; set; } + /// The recovery point name. + string RecoveryPointName { get; set; } + /// The replication extension name. + string ReplicationExtensionName { 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; } + /// The vault name. + string VaultName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.json.cs new file mode 100644 index 00000000000..2216db941fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RecoveryServicesDataReplicationIdentity.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + public partial class RecoveryServicesDataReplicationIdentity + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new RecoveryServicesDataReplicationIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RecoveryServicesDataReplicationIdentity(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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;} + {_vaultName = If( json?.PropertyT("vaultName"), out var __jsonVaultName) ? (string)__jsonVaultName : (string)_vaultName;} + {_emailConfigurationName = If( json?.PropertyT("emailConfigurationName"), out var __jsonEmailConfigurationName) ? (string)__jsonEmailConfigurationName : (string)_emailConfigurationName;} + {_eventName = If( json?.PropertyT("eventName"), out var __jsonEventName) ? (string)__jsonEventName : (string)_eventName;} + {_fabricName = If( json?.PropertyT("fabricName"), out var __jsonFabricName) ? (string)__jsonFabricName : (string)_fabricName;} + {_fabricAgentName = If( json?.PropertyT("fabricAgentName"), out var __jsonFabricAgentName) ? (string)__jsonFabricAgentName : (string)_fabricAgentName;} + {_jobName = If( json?.PropertyT("jobName"), out var __jsonJobName) ? (string)__jsonJobName : (string)_jobName;} + {_policyName = If( json?.PropertyT("policyName"), out var __jsonPolicyName) ? (string)__jsonPolicyName : (string)_policyName;} + {_privateEndpointConnectionName = If( json?.PropertyT("privateEndpointConnectionName"), out var __jsonPrivateEndpointConnectionName) ? (string)__jsonPrivateEndpointConnectionName : (string)_privateEndpointConnectionName;} + {_privateEndpointConnectionProxyName = If( json?.PropertyT("privateEndpointConnectionProxyName"), out var __jsonPrivateEndpointConnectionProxyName) ? (string)__jsonPrivateEndpointConnectionProxyName : (string)_privateEndpointConnectionProxyName;} + {_privateLinkResourceName = If( json?.PropertyT("privateLinkResourceName"), out var __jsonPrivateLinkResourceName) ? (string)__jsonPrivateLinkResourceName : (string)_privateLinkResourceName;} + {_protectedItemName = If( json?.PropertyT("protectedItemName"), out var __jsonProtectedItemName) ? (string)__jsonProtectedItemName : (string)_protectedItemName;} + {_recoveryPointName = If( json?.PropertyT("recoveryPointName"), out var __jsonRecoveryPointName) ? (string)__jsonRecoveryPointName : (string)_recoveryPointName;} + {_replicationExtensionName = If( json?.PropertyT("replicationExtensionName"), out var __jsonReplicationExtensionName) ? (string)__jsonReplicationExtensionName : (string)_replicationExtensionName;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + {_deploymentId = If( json?.PropertyT("deploymentId"), out var __jsonDeploymentId) ? (string)__jsonDeploymentId : (string)_deploymentId;} + {_operationId = If( json?.PropertyT("operationId"), out var __jsonOperationId) ? (string)__jsonOperationId : (string)_operationId;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._vaultName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._vaultName.ToString()) : null, "vaultName" ,container.Add ); + AddIf( null != (((object)this._emailConfigurationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._emailConfigurationName.ToString()) : null, "emailConfigurationName" ,container.Add ); + AddIf( null != (((object)this._eventName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._eventName.ToString()) : null, "eventName" ,container.Add ); + AddIf( null != (((object)this._fabricName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricName.ToString()) : null, "fabricName" ,container.Add ); + AddIf( null != (((object)this._fabricAgentName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricAgentName.ToString()) : null, "fabricAgentName" ,container.Add ); + AddIf( null != (((object)this._jobName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._jobName.ToString()) : null, "jobName" ,container.Add ); + AddIf( null != (((object)this._policyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._policyName.ToString()) : null, "policyName" ,container.Add ); + AddIf( null != (((object)this._privateEndpointConnectionName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._privateEndpointConnectionName.ToString()) : null, "privateEndpointConnectionName" ,container.Add ); + AddIf( null != (((object)this._privateEndpointConnectionProxyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._privateEndpointConnectionProxyName.ToString()) : null, "privateEndpointConnectionProxyName" ,container.Add ); + AddIf( null != (((object)this._privateLinkResourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._privateLinkResourceName.ToString()) : null, "privateLinkResourceName" ,container.Add ); + AddIf( null != (((object)this._protectedItemName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._protectedItemName.ToString()) : null, "protectedItemName" ,container.Add ); + AddIf( null != (((object)this._recoveryPointName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._recoveryPointName.ToString()) : null, "recoveryPointName" ,container.Add ); + AddIf( null != (((object)this._replicationExtensionName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._replicationExtensionName.ToString()) : null, "replicationExtensionName" ,container.Add ); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != (((object)this._deploymentId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._deploymentId.ToString()) : null, "deploymentId" ,container.Add ); + AddIf( null != (((object)this._operationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._operationId.ToString()) : null, "operationId" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.PowerShell.cs new file mode 100644 index 00000000000..4005bc6dcbc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.PowerShell.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// Represent remote private endpoint information for the private endpoint connection proxy. + /// + [System.ComponentModel.TypeConverter(typeof(RemotePrivateEndpointTypeConverter))] + public partial class RemotePrivateEndpoint + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RemotePrivateEndpoint(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RemotePrivateEndpoint(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RemotePrivateEndpoint(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("PrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("ManualPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ManualPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("ManualPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ManualPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("PrivateLinkServiceProxy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceProxy = (System.Collections.Generic.List) content.GetValueForProperty("PrivateLinkServiceProxy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceProxy, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxyTypeConverter.ConvertFrom)); + } + if (content.Contains("ConnectionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ConnectionDetail = (System.Collections.Generic.List) content.GetValueForProperty("ConnectionDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ConnectionDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetailsTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal RemotePrivateEndpoint(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("PrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("PrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("ManualPrivateLinkServiceConnection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ManualPrivateLinkServiceConnection = (System.Collections.Generic.List) content.GetValueForProperty("ManualPrivateLinkServiceConnection",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ManualPrivateLinkServiceConnection, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnectionTypeConverter.ConvertFrom)); + } + if (content.Contains("PrivateLinkServiceProxy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceProxy = (System.Collections.Generic.List) content.GetValueForProperty("PrivateLinkServiceProxy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).PrivateLinkServiceProxy, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxyTypeConverter.ConvertFrom)); + } + if (content.Contains("ConnectionDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ConnectionDetail = (System.Collections.Generic.List) content.GetValueForProperty("ConnectionDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal)this).ConnectionDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetailsTypeConverter.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.RecoveryServicesDataReplication.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(); + } + } + /// Represent remote private endpoint information for the private endpoint connection proxy. + [System.ComponentModel.TypeConverter(typeof(RemotePrivateEndpointTypeConverter))] + public partial interface IRemotePrivateEndpoint + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.TypeConverter.cs new file mode 100644 index 00000000000..84da1f77507 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RemotePrivateEndpointTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RemotePrivateEndpoint.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RemotePrivateEndpoint.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RemotePrivateEndpoint.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.cs new file mode 100644 index 00000000000..be440e43b8e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Represent remote private endpoint information for the private endpoint connection proxy. + /// + public partial class RemotePrivateEndpoint : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _connectionDetail; + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ConnectionDetail { get => this._connectionDetail; set => this._connectionDetail = value; } + + /// Backing field for property. + private string _id; + + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private System.Collections.Generic.List _manualPrivateLinkServiceConnection; + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ManualPrivateLinkServiceConnection { get => this._manualPrivateLinkServiceConnection; set => this._manualPrivateLinkServiceConnection = value; } + + /// Backing field for property. + private System.Collections.Generic.List _privateLinkServiceConnection; + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List PrivateLinkServiceConnection { get => this._privateLinkServiceConnection; set => this._privateLinkServiceConnection = value; } + + /// Backing field for property. + private System.Collections.Generic.List _privateLinkServiceProxy; + + /// Gets or sets the list of private link service proxies. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List PrivateLinkServiceProxy { get => this._privateLinkServiceProxy; set => this._privateLinkServiceProxy = value; } + + /// Creates an new instance. + public RemotePrivateEndpoint() + { + + } + } + /// Represent remote private endpoint information for the private endpoint connection proxy. + public partial interface IRemotePrivateEndpoint : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + System.Collections.Generic.List ConnectionDetail { get; set; } + /// Gets or sets private link service proxy id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + System.Collections.Generic.List ManualPrivateLinkServiceConnection { get; set; } + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + System.Collections.Generic.List PrivateLinkServiceConnection { get; set; } + /// Gets or sets the list of private link service proxies. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + System.Collections.Generic.List PrivateLinkServiceProxy { get; set; } + + } + /// Represent remote private endpoint information for the private endpoint connection proxy. + internal partial interface IRemotePrivateEndpointInternal + + { + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + System.Collections.Generic.List ConnectionDetail { get; set; } + /// Gets or sets private link service proxy id. + string Id { get; set; } + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + System.Collections.Generic.List ManualPrivateLinkServiceConnection { get; set; } + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + System.Collections.Generic.List PrivateLinkServiceConnection { get; set; } + /// Gets or sets the list of private link service proxies. + System.Collections.Generic.List PrivateLinkServiceProxy { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.json.cs new file mode 100644 index 00000000000..337aa9dcfd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpoint.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Represent remote private endpoint information for the private endpoint connection proxy. + /// + public partial class RemotePrivateEndpoint + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpoint FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new RemotePrivateEndpoint(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RemotePrivateEndpoint(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_privateLinkServiceConnection = If( json?.PropertyT("privateLinkServiceConnections"), out var __jsonPrivateLinkServiceConnections) ? If( __jsonPrivateLinkServiceConnections as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnection.FromJson(__u) )) ))() : null : _privateLinkServiceConnection;} + {_manualPrivateLinkServiceConnection = If( json?.PropertyT("manualPrivateLinkServiceConnections"), out var __jsonManualPrivateLinkServiceConnections) ? If( __jsonManualPrivateLinkServiceConnections as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceConnection.FromJson(__p) )) ))() : null : _manualPrivateLinkServiceConnection;} + {_privateLinkServiceProxy = If( json?.PropertyT("privateLinkServiceProxies"), out var __jsonPrivateLinkServiceProxies) ? If( __jsonPrivateLinkServiceProxies as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateLinkServiceProxy.FromJson(__k) )) ))() : null : _privateLinkServiceProxy;} + {_connectionDetail = If( json?.PropertyT("connectionDetails"), out var __jsonConnectionDetails) ? If( __jsonConnectionDetails as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __g) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__g, (__f)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ConnectionDetails.FromJson(__f) )) ))() : null : _connectionDetail;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + if (null != this._privateLinkServiceConnection) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._privateLinkServiceConnection ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("privateLinkServiceConnections",__w); + } + if (null != this._manualPrivateLinkServiceConnection) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._manualPrivateLinkServiceConnection ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("manualPrivateLinkServiceConnections",__r); + } + if (null != this._privateLinkServiceProxy) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __n in this._privateLinkServiceProxy ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("privateLinkServiceProxies",__m); + } + if (null != this._connectionDetail) + { + var __h = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __i in this._connectionDetail ) + { + AddIf(__i?.ToJson(null, serializationMode) ,__h.Add); + } + container.Add("connectionDetails",__h); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.PowerShell.cs new file mode 100644 index 00000000000..8b561e3d6ec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Represent remote private endpoint connection. + [System.ComponentModel.TypeConverter(typeof(RemotePrivateEndpointConnectionTypeConverter))] + public partial class RemotePrivateEndpointConnection + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RemotePrivateEndpointConnection(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RemotePrivateEndpointConnection(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RemotePrivateEndpointConnection(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal)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 RemotePrivateEndpointConnection(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal)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.RecoveryServicesDataReplication.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(); + } + } + /// Represent remote private endpoint connection. + [System.ComponentModel.TypeConverter(typeof(RemotePrivateEndpointConnectionTypeConverter))] + public partial interface IRemotePrivateEndpointConnection + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.TypeConverter.cs new file mode 100644 index 00000000000..661240424d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RemotePrivateEndpointConnectionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RemotePrivateEndpointConnection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RemotePrivateEndpointConnection.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RemotePrivateEndpointConnection.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.cs new file mode 100644 index 00000000000..a353147a98c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represent remote private endpoint connection. + public partial class RemotePrivateEndpointConnection : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnectionInternal + { + + /// Backing field for property. + private string _id; + + /// Gets or sets the remote private endpoint connection id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Creates an new instance. + public RemotePrivateEndpointConnection() + { + + } + } + /// Represent remote private endpoint connection. + public partial interface IRemotePrivateEndpointConnection : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the remote private endpoint connection id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the remote private endpoint connection id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + + } + /// Represent remote private endpoint connection. + internal partial interface IRemotePrivateEndpointConnectionInternal + + { + /// Gets or sets the remote private endpoint connection id. + string Id { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.json.cs new file mode 100644 index 00000000000..9f987222e29 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/RemotePrivateEndpointConnection.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Represent remote private endpoint connection. + public partial class RemotePrivateEndpointConnection + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRemotePrivateEndpointConnection FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new RemotePrivateEndpointConnection(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal RemotePrivateEndpointConnection(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.PowerShell.cs new file mode 100644 index 00000000000..9bbd2f140d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.PowerShell.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Replication extension model. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelTypeConverter))] + public partial class ReplicationExtensionModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ReplicationExtensionModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ReplicationExtensionModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ReplicationExtensionModel(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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomPropertyInstanceType, 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 ReplicationExtensionModel(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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Replication extension model. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelTypeConverter))] + public partial interface IReplicationExtensionModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.TypeConverter.cs new file mode 100644 index 00000000000..e646044116d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ReplicationExtensionModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ReplicationExtensionModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ReplicationExtensionModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ReplicationExtensionModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.cs new file mode 100644 index 00000000000..0cd3e1fab26 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Replication extension model. + public partial class ReplicationExtensionModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(); + + /// Replication extension model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).CustomPropertyInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).CustomPropertyInstanceType = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal.CustomProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).CustomProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).CustomProperty = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the replication extension. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public ReplicationExtensionModel() + { + + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Replication extension model. + public partial interface IReplicationExtensionModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResource + { + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the replication extension. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the replication extension.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Replication extension model. + internal partial interface IReplicationExtensionModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProxyResourceInternal + { + /// Replication extension model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for ReplicationExtensionModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the replication extension. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.json.cs new file mode 100644 index 00000000000..1cda6329530 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Replication extension model. + public partial class ReplicationExtensionModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ReplicationExtensionModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ReplicationExtensionModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelProperties.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..d435481e998 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.PowerShell.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Replication extension model custom properties. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelCustomPropertiesTypeConverter))] + public partial class ReplicationExtensionModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ReplicationExtensionModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ReplicationExtensionModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ReplicationExtensionModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType, 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 ReplicationExtensionModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Replication extension model custom properties. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelCustomPropertiesTypeConverter))] + public partial interface IReplicationExtensionModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..c66d523943b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ReplicationExtensionModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ReplicationExtensionModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ReplicationExtensionModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ReplicationExtensionModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.cs new file mode 100644 index 00000000000..2125064201e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Replication extension model custom properties. + public partial class ReplicationExtensionModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// + /// Creates an new instance. + /// + public ReplicationExtensionModelCustomProperties() + { + + } + } + /// Replication extension model custom properties. + public partial interface IReplicationExtensionModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Replication extension model custom properties. + internal partial interface IReplicationExtensionModelCustomPropertiesInternal + + { + /// Discriminator property for ReplicationExtensionModelCustomProperties. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.json.cs new file mode 100644 index 00000000000..5e1b5c126f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Replication extension model custom properties. + public partial class ReplicationExtensionModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties. + /// Note: the Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties + /// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the + /// payload. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + if (!(node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json)) + { + return null; + } + // Polymorphic type -- select the appropriate constructor using the discriminator + + switch ( json.StringProperty("instanceType") ) + { + case "HyperVToAzStackHCI": + { + return new HyperVToAzStackHcireplicationExtensionModelCustomProperties(json); + } + case "VMwareToAzStackHCI": + { + return new VMwareToAzStackHcireplicationExtensionModelCustomProperties(json); + } + } + return new ReplicationExtensionModelCustomProperties(json); + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ReplicationExtensionModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.PowerShell.cs new file mode 100644 index 00000000000..eacdcffa4df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a ReplicationExtensionModel list operation. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelListResultTypeConverter))] + public partial class ReplicationExtensionModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ReplicationExtensionModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ReplicationExtensionModelListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ReplicationExtensionModelListResult(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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)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 ReplicationExtensionModelListResult(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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal)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.RecoveryServicesDataReplication.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 ReplicationExtensionModel list operation. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelListResultTypeConverter))] + public partial interface IReplicationExtensionModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..14eec3509e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ReplicationExtensionModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ReplicationExtensionModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ReplicationExtensionModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ReplicationExtensionModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.cs new file mode 100644 index 00000000000..4adda738c37 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a ReplicationExtensionModel list operation. + public partial class ReplicationExtensionModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The ReplicationExtensionModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ReplicationExtensionModelListResult() + { + + } + } + /// The response of a ReplicationExtensionModel list operation. + public partial interface IReplicationExtensionModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 ReplicationExtensionModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ReplicationExtensionModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a ReplicationExtensionModel list operation. + internal partial interface IReplicationExtensionModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The ReplicationExtensionModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.json.cs new file mode 100644 index 00000000000..979095f0ce1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelListResult.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a ReplicationExtensionModel list operation. + public partial class ReplicationExtensionModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ReplicationExtensionModelListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ReplicationExtensionModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.PowerShell.cs new file mode 100644 index 00000000000..707014350ca --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.PowerShell.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Replication extension model properties. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelPropertiesTypeConverter))] + public partial class ReplicationExtensionModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ReplicationExtensionModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ReplicationExtensionModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ReplicationExtensionModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomPropertyInstanceType, 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 ReplicationExtensionModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Replication extension model properties. + [System.ComponentModel.TypeConverter(typeof(ReplicationExtensionModelPropertiesTypeConverter))] + public partial interface IReplicationExtensionModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..710e0befeb3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ReplicationExtensionModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ReplicationExtensionModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ReplicationExtensionModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ReplicationExtensionModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.cs new file mode 100644 index 00000000000..532d075ea2b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Replication extension model properties. + public partial class ReplicationExtensionModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties _customProperty; + + /// Replication extension model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties()); set => this._customProperty = value; } + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)CustomProperty).InstanceType = value ; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the replication extension. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Creates an new instance. + public ReplicationExtensionModelProperties() + { + + } + } + /// Replication extension model properties. + public partial interface IReplicationExtensionModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the replication extension. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the replication extension.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Replication extension model properties. + internal partial interface IReplicationExtensionModelPropertiesInternal + + { + /// Replication extension model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties CustomProperty { get; set; } + /// Discriminator property for ReplicationExtensionModelCustomProperties. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the provisioning state of the replication extension. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.json.cs new file mode 100644 index 00000000000..fc5f9b9c7ec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/ReplicationExtensionModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Replication extension model properties. + public partial class ReplicationExtensionModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new ReplicationExtensionModelProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal ReplicationExtensionModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..8a82017d4a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..6db039f3aff --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..7c93b63c7de --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Resource.cs @@ -0,0 +1,255 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// 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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..f47ac09ca4b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.PowerShell.cs new file mode 100644 index 00000000000..1cbce91452c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Storage container properties. + [System.ComponentModel.TypeConverter(typeof(StorageContainerPropertiesTypeConverter))] + public partial class StorageContainerProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IStorageContainerProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new StorageContainerProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new StorageContainerProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal StorageContainerProperties(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.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("ClusterSharedVolumePath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).ClusterSharedVolumePath = (string) content.GetValueForProperty("ClusterSharedVolumePath",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).ClusterSharedVolumePath, 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 StorageContainerProperties(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.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("ClusterSharedVolumePath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).ClusterSharedVolumePath = (string) content.GetValueForProperty("ClusterSharedVolumePath",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal)this).ClusterSharedVolumePath, 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.RecoveryServicesDataReplication.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(); + } + } + /// Storage container properties. + [System.ComponentModel.TypeConverter(typeof(StorageContainerPropertiesTypeConverter))] + public partial interface IStorageContainerProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.TypeConverter.cs new file mode 100644 index 00000000000..3ba1aea7fdd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class StorageContainerPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IStorageContainerProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return StorageContainerProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return StorageContainerProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return StorageContainerProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.cs new file mode 100644 index 00000000000..e43bf3d5ec3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Storage container properties. + public partial class StorageContainerProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerPropertiesInternal + { + + /// Backing field for property. + private string _clusterSharedVolumePath; + + /// Gets or sets the ClusterSharedVolumePath. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ClusterSharedVolumePath { get => this._clusterSharedVolumePath; set => this._clusterSharedVolumePath = value; } + + /// Backing field for property. + private string _name; + + /// Gets or sets the Name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public StorageContainerProperties() + { + + } + } + /// Storage container properties. + public partial interface IStorageContainerProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the ClusterSharedVolumePath. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ClusterSharedVolumePath.", + SerializedName = @"clusterSharedVolumePath", + PossibleTypes = new [] { typeof(string) })] + string ClusterSharedVolumePath { get; set; } + /// Gets or sets the Name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Storage container properties. + internal partial interface IStorageContainerPropertiesInternal + + { + /// Gets or sets the ClusterSharedVolumePath. + string ClusterSharedVolumePath { get; set; } + /// Gets or sets the Name. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.json.cs new file mode 100644 index 00000000000..96d4c09a02e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/StorageContainerProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Storage container properties. + public partial class StorageContainerProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IStorageContainerProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new StorageContainerProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal StorageContainerProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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;} + {_clusterSharedVolumePath = If( json?.PropertyT("clusterSharedVolumePath"), out var __jsonClusterSharedVolumePath) ? (string)__jsonClusterSharedVolumePath : (string)_clusterSharedVolumePath;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._clusterSharedVolumePath)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._clusterSharedVolumePath.ToString()) : null, "clusterSharedVolumePath" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..e3d66335b9e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..3e2edce532d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..b4ec698b316 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..dd664020584 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/TaskModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.PowerShell.cs new file mode 100644 index 00000000000..1f6b84197ee --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Task model. + [System.ComponentModel.TypeConverter(typeof(TaskModelTypeConverter))] + public partial class TaskModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.ITaskModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TaskModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TaskModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TaskModel(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("TaskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).TaskName = (string) content.GetValueForProperty("TaskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).TaskName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("ChildrenJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).ChildrenJob = (System.Collections.Generic.List) content.GetValueForProperty("ChildrenJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).ChildrenJob, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomPropertyInstanceType, 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 TaskModel(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CustomProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomProperty = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties) content.GetValueForProperty("CustomProperty",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomProperty, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelCustomPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("TaskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).TaskName = (string) content.GetValueForProperty("TaskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).TaskName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EndTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).EndTime = (global::System.DateTime?) content.GetValueForProperty("EndTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).EndTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("ChildrenJob")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).ChildrenJob = (System.Collections.Generic.List) content.GetValueForProperty("ChildrenJob",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).ChildrenJob, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelTypeConverter.ConvertFrom)); + } + if (content.Contains("CustomPropertyInstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomPropertyInstanceType = (string) content.GetValueForProperty("CustomPropertyInstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal)this).CustomPropertyInstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Task model. + [System.ComponentModel.TypeConverter(typeof(TaskModelTypeConverter))] + public partial interface ITaskModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.TypeConverter.cs new file mode 100644 index 00000000000..d1eb694dbb9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TaskModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ITaskModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TaskModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TaskModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TaskModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/TaskModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.cs new file mode 100644 index 00000000000..c618224228e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Task model. + public partial class TaskModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _childrenJob; + + /// Gets or sets the list of children job models. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ChildrenJob { get => this._childrenJob; set => this._childrenJob = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties _customProperty; + + /// Task model custom properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelCustomProperties()); set => this._customProperty = value; } + + /// Gets or sets the instance type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string CustomPropertyInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal)CustomProperty).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal)CustomProperty).InstanceType = value ?? null; } + + /// Backing field for property. + private global::System.DateTime? _endTime; + + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? EndTime { get => this._endTime; } + + /// Internal Acessors for CustomProperty + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal.CustomProperty { get => (this._customProperty = this._customProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelCustomProperties()); set { {_customProperty = value;} } } + + /// Internal Acessors for EndTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal.EndTime { get => this._endTime; set { {_endTime = value;} } } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal.StartTime { get => this._startTime; set { {_startTime = value;} } } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal.State { get => this._state; set { {_state = value;} } } + + /// Internal Acessors for TaskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelInternal.TaskName { get => this._taskName; set { {_taskName = value;} } } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; } + + /// Backing field for property. + private string _state; + + /// Gets or sets the task state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string State { get => this._state; } + + /// Backing field for property. + private string _taskName; + + /// Gets or sets the task name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TaskName { get => this._taskName; } + + /// Creates an new instance. + public TaskModel() + { + + } + } + /// Task model. + public partial interface ITaskModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the list of children job models. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of children job models.", + SerializedName = @"childrenJobs", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel) })] + System.Collections.Generic.List ChildrenJob { get; set; } + /// Gets or sets the instance type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the instance type.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the end time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the end time.", + SerializedName = @"endTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndTime { get; } + /// Gets or sets the start time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the start time.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// Gets or sets the task state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the task state.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Pending", "Started", "Succeeded", "Failed", "Cancelled", "Skipped")] + string State { get; } + /// Gets or sets the task name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the task name.", + SerializedName = @"taskName", + PossibleTypes = new [] { typeof(string) })] + string TaskName { get; } + + } + /// Task model. + internal partial interface ITaskModelInternal + + { + /// Gets or sets the list of children job models. + System.Collections.Generic.List ChildrenJob { get; set; } + /// Task model custom properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties CustomProperty { get; set; } + /// Gets or sets the instance type. + string CustomPropertyInstanceType { get; set; } + /// Gets or sets the end time. + global::System.DateTime? EndTime { get; set; } + /// Gets or sets the start time. + global::System.DateTime? StartTime { get; set; } + /// Gets or sets the task state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Pending", "Started", "Succeeded", "Failed", "Cancelled", "Skipped")] + string State { get; set; } + /// Gets or sets the task name. + string TaskName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.json.cs new file mode 100644 index 00000000000..0547cf854e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModel.json.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Task model. + public partial class TaskModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new TaskModel(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal TaskModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_customProperty = If( json?.PropertyT("customProperties"), out var __jsonCustomProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TaskModelCustomProperties.FromJson(__jsonCustomProperties) : _customProperty;} + {_taskName = If( json?.PropertyT("taskName"), out var __jsonTaskName) ? (string)__jsonTaskName : (string)_taskName;} + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_endTime = If( json?.PropertyT("endTime"), out var __jsonEndTime) ? global::System.DateTime.TryParse((string)__jsonEndTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndTimeValue) ? __jsonEndTimeValue : _endTime : _endTime;} + {_childrenJob = If( json?.PropertyT("childrenJobs"), out var __jsonChildrenJobs) ? If( __jsonChildrenJobs as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModel.FromJson(__u) )) ))() : null : _childrenJob;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._customProperty ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._customProperty.ToJson(null,serializationMode) : null, "customProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._taskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._taskName.ToString()) : null, "taskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._endTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._endTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endTime" ,container.Add ); + } + if (null != this._childrenJob) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._childrenJob ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("childrenJobs",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..bba26f4666d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Task model custom properties. + [System.ComponentModel.TypeConverter(typeof(TaskModelCustomPropertiesTypeConverter))] + public partial class TaskModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TaskModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TaskModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TaskModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal)this).InstanceType, 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 TaskModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Task model custom properties. + [System.ComponentModel.TypeConverter(typeof(TaskModelCustomPropertiesTypeConverter))] + public partial interface ITaskModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..a867fd1ee9a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TaskModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TaskModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TaskModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TaskModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.cs new file mode 100644 index 00000000000..79ab8ba5b8a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Task model custom properties. + public partial class TaskModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomPropertiesInternal + { + + /// Backing field for property. + private string _instanceType; + + /// Gets or sets the instance type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string InstanceType { get => this._instanceType; set => this._instanceType = value; } + + /// Creates an new instance. + public TaskModelCustomProperties() + { + + } + } + /// Task model custom properties. + public partial interface ITaskModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the instance type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the instance type.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + string InstanceType { get; set; } + + } + /// Task model custom properties. + internal partial interface ITaskModelCustomPropertiesInternal + + { + /// Gets or sets the instance type. + string InstanceType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.json.cs new file mode 100644 index 00000000000..c8e36c7a5c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TaskModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Task model custom properties. + public partial class TaskModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITaskModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new TaskModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal TaskModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_instanceType = If( json?.PropertyT("instanceType"), out var __jsonInstanceType) ? (string)__jsonInstanceType : (string)_instanceType;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._instanceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._instanceType.ToString()) : null, "instanceType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..60995c3edcc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Test failover cleanup job model custom properties. + [System.ComponentModel.TypeConverter(typeof(TestFailoverCleanupJobModelCustomPropertiesTypeConverter))] + public partial class TestFailoverCleanupJobModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TestFailoverCleanupJobModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TestFailoverCleanupJobModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a + /// json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TestFailoverCleanupJobModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Comment")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomPropertiesInternal)this).Comment = (string) content.GetValueForProperty("Comment",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomPropertiesInternal)this).Comment, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, 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 TestFailoverCleanupJobModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Comment")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomPropertiesInternal)this).Comment = (string) content.GetValueForProperty("Comment",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomPropertiesInternal)this).Comment, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Test failover cleanup job model custom properties. + [System.ComponentModel.TypeConverter(typeof(TestFailoverCleanupJobModelCustomPropertiesTypeConverter))] + public partial interface ITestFailoverCleanupJobModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..21a870f9b30 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TestFailoverCleanupJobModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TestFailoverCleanupJobModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TestFailoverCleanupJobModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TestFailoverCleanupJobModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.cs new file mode 100644 index 00000000000..d018eaf6ee9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Test failover cleanup job model custom properties. + public partial class TestFailoverCleanupJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties __jobModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties(); + + /// Gets or sets any custom properties of the affected object. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails AffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail = value ?? null /* model class */; } + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription; } + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType; } + + /// Backing field for property. + private string _comment; + + /// Gets or sets the test failover cleanup comments. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Comment { get => this._comment; } + + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "TestFailoverCleanupJobDetails"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).InstanceType = "TestFailoverCleanupJobDetails"; } + + /// Internal Acessors for AffectedObjectDetail + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail = value ?? null /* model class */; } + + /// Internal Acessors for AffectedObjectDetailDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType = value ?? null; } + + /// Internal Acessors for Comment + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomPropertiesInternal.Comment { get => this._comment; set { {_comment = value;} } } + + /// + /// Creates an new instance. + /// + public TestFailoverCleanupJobModelCustomProperties() + { + this.__jobModelCustomProperties.InstanceType = "TestFailoverCleanupJobDetails"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__jobModelCustomProperties), __jobModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__jobModelCustomProperties), __jobModelCustomProperties); + } + } + /// Test failover cleanup job model custom properties. + public partial interface ITestFailoverCleanupJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties + { + /// Gets or sets the test failover cleanup comments. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test failover cleanup comments.", + SerializedName = @"comments", + PossibleTypes = new [] { typeof(string) })] + string Comment { get; } + + } + /// Test failover cleanup job model custom properties. + internal partial interface ITestFailoverCleanupJobModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal + { + /// Gets or sets the test failover cleanup comments. + string Comment { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.json.cs new file mode 100644 index 00000000000..ad52b4032ab --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverCleanupJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Test failover cleanup job model custom properties. + public partial class TestFailoverCleanupJobModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverCleanupJobModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new TestFailoverCleanupJobModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal TestFailoverCleanupJobModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __jobModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties(json); + {_comment = If( json?.PropertyT("comments"), out var __jsonComments) ? (string)__jsonComments : (string)_comment;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __jobModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._comment)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._comment.ToString()) : null, "comments" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..3ae3bb27fcd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.PowerShell.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Test failover job model custom properties. + [System.ComponentModel.TypeConverter(typeof(TestFailoverJobModelCustomPropertiesTypeConverter))] + public partial class TestFailoverJobModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TestFailoverJobModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TestFailoverJobModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TestFailoverJobModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProtectedItemDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedItemDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FailoverProtectedItemPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, 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 TestFailoverJobModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProtectedItemDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedItemDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomPropertiesInternal)this).ProtectedItemDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FailoverProtectedItemPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("AffectedObjectDetailType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType = (string) content.GetValueForProperty("AffectedObjectDetailType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailType, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetailDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription = (string) content.GetValueForProperty("AffectedObjectDetailDescription",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetailDescription, global::System.Convert.ToString); + } + if (content.Contains("AffectedObjectDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails) content.GetValueForProperty("AffectedObjectDetail",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).AffectedObjectDetail, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.AffectedObjectDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)this).InstanceType, 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.RecoveryServicesDataReplication.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(); + } + } + /// Test failover job model custom properties. + [System.ComponentModel.TypeConverter(typeof(TestFailoverJobModelCustomPropertiesTypeConverter))] + public partial interface ITestFailoverJobModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..3742c4f53cc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TestFailoverJobModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TestFailoverJobModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TestFailoverJobModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TestFailoverJobModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.cs new file mode 100644 index 00000000000..18434df1112 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Test failover job model custom properties. + public partial class TestFailoverJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties __jobModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties(); + + /// Gets or sets any custom properties of the affected object. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails AffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail = value ?? null /* model class */; } + + /// Description of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription; } + + /// Type of the affected object details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType; } + + /// Discriminator property for JobModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "TestFailoverJobDetails"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).InstanceType = "TestFailoverJobDetails"; } + + /// Internal Acessors for AffectedObjectDetail + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IAffectedObjectDetails Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetail = value ?? null /* model class */; } + + /// Internal Acessors for AffectedObjectDetailDescription + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailDescription = value ?? null; } + + /// Internal Acessors for AffectedObjectDetailType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal.AffectedObjectDetailType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal)__jobModelCustomProperties).AffectedObjectDetailType = value ?? null; } + + /// Internal Acessors for ProtectedItemDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomPropertiesInternal.ProtectedItemDetail { get => this._protectedItemDetail; set { {_protectedItemDetail = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _protectedItemDetail; + + /// Gets or sets the test VM details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ProtectedItemDetail { get => this._protectedItemDetail; } + + /// Creates an new instance. + public TestFailoverJobModelCustomProperties() + { + this.__jobModelCustomProperties.InstanceType = "TestFailoverJobDetails"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__jobModelCustomProperties), __jobModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__jobModelCustomProperties), __jobModelCustomProperties); + } + } + /// Test failover job model custom properties. + public partial interface ITestFailoverJobModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomProperties + { + /// Gets or sets the test VM details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test VM details.", + SerializedName = @"protectedItemDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties) })] + System.Collections.Generic.List ProtectedItemDetail { get; } + + } + /// Test failover job model custom properties. + internal partial interface ITestFailoverJobModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModelCustomPropertiesInternal + { + /// Gets or sets the test VM details. + System.Collections.Generic.List ProtectedItemDetail { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.json.cs new file mode 100644 index 00000000000..c93d0a9bc4a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TestFailoverJobModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Test failover job model custom properties. + public partial class TestFailoverJobModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITestFailoverJobModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new TestFailoverJobModelCustomProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal TestFailoverJobModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __jobModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.JobModelCustomProperties(json); + {_protectedItemDetail = If( json?.PropertyT("protectedItemDetails"), out var __jsonProtectedItemDetails) ? If( __jsonProtectedItemDetails as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFailoverProtectedItemProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FailoverProtectedItemProperties.FromJson(__u) )) ))() : null : _protectedItemDetail;} + 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __jobModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._protectedItemDetail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._protectedItemDetail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("protectedItemDetails",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..54027914737 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs @@ -0,0 +1,254 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..6acaaf219ec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..695572f9edc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + 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.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags 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.RecoveryServicesDataReplication.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..4d57750faab --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTags.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/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs new file mode 100644 index 00000000000..6ccce837ad0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial class TrackedResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// 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.RecoveryServicesDataReplication.Models.ITrackedResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 TrackedResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial interface ITrackedResourceTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs new file mode 100644 index 00000000000..af4b7191fbf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.ITrackedResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.cs new file mode 100644 index 00000000000..f7c336e2113 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTagsInternal + { + + /// Creates an new instance. + public TrackedResourceTags() + { + + } + } + /// Resource tags. + public partial interface ITrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITrackedResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs new file mode 100644 index 00000000000..acf14617d76 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.TrackedResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs new file mode 100644 index 00000000000..bdae15d1da1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/TrackedResourceTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new TrackedResourceTags(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TrackedResourceTags(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs new file mode 100644 index 00000000000..a3dc26040dc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IUserAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs new file mode 100644 index 00000000000..e6c353e259c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IUserAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs new file mode 100644 index 00000000000..92efaebe70e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal + { + + /// Backing field for property. + private string _clientId; + + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentityInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs new file mode 100644 index 00000000000..55c80b69848 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IUserAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..759329f2968 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware fabric agent model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareFabricAgentModelCustomPropertiesTypeConverter))] + public partial class VMwareFabricAgentModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareFabricAgentModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareFabricAgentModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareFabricAgentModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarsAuthenticationIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarsAuthenticationIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("MarsAuthenticationIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarsAuthenticationIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("BiosId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).BiosId = (string) content.GetValueForProperty("BiosId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).BiosId, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityTenantId = (string) content.GetValueForProperty("MarAuthenticationIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityApplicationId = (string) content.GetValueForProperty("MarAuthenticationIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityObjectId = (string) content.GetValueForProperty("MarAuthenticationIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAudience = (string) content.GetValueForProperty("MarAuthenticationIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAadAuthority = (string) content.GetValueForProperty("MarAuthenticationIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAadAuthority, 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 VMwareFabricAgentModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarsAuthenticationIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarsAuthenticationIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel) content.GetValueForProperty("MarsAuthenticationIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarsAuthenticationIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("BiosId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).BiosId = (string) content.GetValueForProperty("BiosId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).BiosId, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityTenantId = (string) content.GetValueForProperty("MarAuthenticationIdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityApplicationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityApplicationId = (string) content.GetValueForProperty("MarAuthenticationIdentityApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityApplicationId, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityObjectId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityObjectId = (string) content.GetValueForProperty("MarAuthenticationIdentityObjectId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityObjectId, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityAudience")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAudience = (string) content.GetValueForProperty("MarAuthenticationIdentityAudience",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAudience, global::System.Convert.ToString); + } + if (content.Contains("MarAuthenticationIdentityAadAuthority")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAadAuthority = (string) content.GetValueForProperty("MarAuthenticationIdentityAadAuthority",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal)this).MarAuthenticationIdentityAadAuthority, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware fabric agent model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareFabricAgentModelCustomPropertiesTypeConverter))] + public partial interface IVMwareFabricAgentModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..4a6c36dd930 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareFabricAgentModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareFabricAgentModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareFabricAgentModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareFabricAgentModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.cs new file mode 100644 index 00000000000..009d3558062 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware fabric agent model custom properties. + public partial class VMwareFabricAgentModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties __fabricAgentModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomProperties(); + + /// Backing field for property. + private string _biosId; + + /// Gets or sets the BIOS Id of the fabric agent machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string BiosId { get => this._biosId; set => this._biosId = value; } + + /// Discriminator property for FabricAgentModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMware"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal)__fabricAgentModelCustomProperties).InstanceType = "VMware"; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MarAuthenticationIdentityAadAuthority { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).AadAuthority; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).AadAuthority = value ; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MarAuthenticationIdentityApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).ApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).ApplicationId = value ; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MarAuthenticationIdentityAudience { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).Audience; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).Audience = value ; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MarAuthenticationIdentityObjectId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).ObjectId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).ObjectId = value ; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string MarAuthenticationIdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModelInternal)MarsAuthenticationIdentity).TenantId = value ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel _marsAuthenticationIdentity; + + /// Identity model. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel MarsAuthenticationIdentity { get => (this._marsAuthenticationIdentity = this._marsAuthenticationIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel()); set => this._marsAuthenticationIdentity = value; } + + /// Internal Acessors for MarsAuthenticationIdentity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomPropertiesInternal.MarsAuthenticationIdentity { get => (this._marsAuthenticationIdentity = this._marsAuthenticationIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel()); set { {_marsAuthenticationIdentity = value;} } } + + /// Creates an new instance. + public VMwareFabricAgentModelCustomProperties() + { + this.__fabricAgentModelCustomProperties.InstanceType = "VMware"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__fabricAgentModelCustomProperties), __fabricAgentModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__fabricAgentModelCustomProperties), __fabricAgentModelCustomProperties); + } + } + /// VMware fabric agent model custom properties. + public partial interface IVMwareFabricAgentModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomProperties + { + /// Gets or sets the BIOS Id of the fabric agent machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the BIOS Id of the fabric agent machine.", + SerializedName = @"biosId", + PossibleTypes = new [] { typeof(string) })] + string BiosId { get; set; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + string MarAuthenticationIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string MarAuthenticationIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + string MarAuthenticationIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string MarAuthenticationIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string MarAuthenticationIdentityTenantId { get; set; } + + } + /// VMware fabric agent model custom properties. + internal partial interface IVMwareFabricAgentModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModelCustomPropertiesInternal + { + /// Gets or sets the BIOS Id of the fabric agent machine. + string BiosId { get; set; } + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + string MarAuthenticationIdentityAadAuthority { get; set; } + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + string MarAuthenticationIdentityApplicationId { get; set; } + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + string MarAuthenticationIdentityAudience { get; set; } + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + string MarAuthenticationIdentityObjectId { get; set; } + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + string MarAuthenticationIdentityTenantId { get; set; } + /// Identity model. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IIdentityModel MarsAuthenticationIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.json.cs new file mode 100644 index 00000000000..172f02312ba --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareFabricAgentModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware fabric agent model custom properties. + public partial class VMwareFabricAgentModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareFabricAgentModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareFabricAgentModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __fabricAgentModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != this._marsAuthenticationIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._marsAuthenticationIdentity.ToJson(null,serializationMode) : null, "marsAuthenticationIdentity" ,container.Add ); + AddIf( null != (((object)this._biosId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._biosId.ToString()) : null, "biosId" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareFabricAgentModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __fabricAgentModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModelCustomProperties(json); + {_marsAuthenticationIdentity = If( json?.PropertyT("marsAuthenticationIdentity"), out var __jsonMarsAuthenticationIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IdentityModel.FromJson(__jsonMarsAuthenticationIdentity) : _marsAuthenticationIdentity;} + {_biosId = If( json?.PropertyT("biosId"), out var __jsonBiosId) ? (string)__jsonBiosId : (string)_biosId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..0495ce5ff54 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware migrate fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareMigrateFabricModelCustomPropertiesTypeConverter))] + public partial class VMwareMigrateFabricModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareMigrateFabricModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareMigrateFabricModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareMigrateFabricModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("VmwareSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).VmwareSiteId = (string) content.GetValueForProperty("VmwareSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).VmwareSiteId, global::System.Convert.ToString); + } + if (content.Contains("MigrationSolutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId = (string) content.GetValueForProperty("MigrationSolutionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, 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 VMwareMigrateFabricModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("VmwareSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).VmwareSiteId = (string) content.GetValueForProperty("VmwareSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).VmwareSiteId, global::System.Convert.ToString); + } + if (content.Contains("MigrationSolutionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId = (string) content.GetValueForProperty("MigrationSolutionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal)this).MigrationSolutionId, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware migrate fabric model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareMigrateFabricModelCustomPropertiesTypeConverter))] + public partial interface IVMwareMigrateFabricModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..d6688eee9c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareMigrateFabricModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareMigrateFabricModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareMigrateFabricModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareMigrateFabricModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.cs new file mode 100644 index 00000000000..5c203031c7a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware migrate fabric model custom properties. + public partial class VMwareMigrateFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties __fabricModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties(); + + /// Discriminator property for FabricModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareMigrate"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal)__fabricModelCustomProperties).InstanceType = "VMwareMigrate"; } + + /// Backing field for property. + private string _migrationSolutionId; + + /// Gets or sets the ARM Id of the migration solution. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrationSolutionId { get => this._migrationSolutionId; set => this._migrationSolutionId = value; } + + /// Backing field for property. + private string _vmwareSiteId; + + /// Gets or sets the ARM Id of the VMware site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VmwareSiteId { get => this._vmwareSiteId; set => this._vmwareSiteId = value; } + + /// + /// Creates an new instance. + /// + public VMwareMigrateFabricModelCustomProperties() + { + this.__fabricModelCustomProperties.InstanceType = "VMwareMigrate"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__fabricModelCustomProperties), __fabricModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__fabricModelCustomProperties), __fabricModelCustomProperties); + } + } + /// VMware migrate fabric model custom properties. + public partial interface IVMwareMigrateFabricModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomProperties + { + /// Gets or sets the ARM Id of the migration solution. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the migration solution.", + SerializedName = @"migrationSolutionId", + PossibleTypes = new [] { typeof(string) })] + string MigrationSolutionId { get; set; } + /// Gets or sets the ARM Id of the VMware site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the VMware site.", + SerializedName = @"vmwareSiteId", + PossibleTypes = new [] { typeof(string) })] + string VmwareSiteId { get; set; } + + } + /// VMware migrate fabric model custom properties. + internal partial interface IVMwareMigrateFabricModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelCustomPropertiesInternal + { + /// Gets or sets the ARM Id of the migration solution. + string MigrationSolutionId { get; set; } + /// Gets or sets the ARM Id of the VMware site. + string VmwareSiteId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.json.cs new file mode 100644 index 00000000000..550af052ec4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareMigrateFabricModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware migrate fabric model custom properties. + public partial class VMwareMigrateFabricModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareMigrateFabricModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareMigrateFabricModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __fabricModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != (((object)this._vmwareSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._vmwareSiteId.ToString()) : null, "vmwareSiteId" ,container.Add ); + AddIf( null != (((object)this._migrationSolutionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrationSolutionId.ToString()) : null, "migrationSolutionId" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareMigrateFabricModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __fabricModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelCustomProperties(json); + {_vmwareSiteId = If( json?.PropertyT("vmwareSiteId"), out var __jsonVmwareSiteId) ? (string)__jsonVmwareSiteId : (string)_vmwareSiteId;} + {_migrationSolutionId = If( json?.PropertyT("migrationSolutionId"), out var __jsonMigrationSolutionId) ? (string)__jsonMigrationSolutionId : (string)_migrationSolutionId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.PowerShell.cs new file mode 100644 index 00000000000..55f567b65d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.PowerShell.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMwareToAzStack disk input. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcidiskInputTypeConverter))] + public partial class VMwareToAzStackHcidiskInput + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHcidiskInput(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHcidiskInput(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHcidiskInput(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskController")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskController = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs) content.GetValueForProperty("DiskController",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskController, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputsTypeConverter.ConvertFrom); + } + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskId = (string) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskSizeGb")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskSizeGb = (long) content.GetValueForProperty("DiskSizeGb",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskSizeGb, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskFileFormat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskFileFormat = (string) content.GetValueForProperty("DiskFileFormat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskFileFormat, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsOSDisk = (bool) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskIdentifier")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskIdentifier = (string) content.GetValueForProperty("DiskIdentifier",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskIdentifier, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerName = (string) content.GetValueForProperty("DiskControllerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerName, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerId = (int?) content.GetValueForProperty("DiskControllerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("DiskControllerLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerLocation = (int?) content.GetValueForProperty("DiskControllerLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerLocation, (__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 VMwareToAzStackHcidiskInput(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskController")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskController = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs) content.GetValueForProperty("DiskController",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskController, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputsTypeConverter.ConvertFrom); + } + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskId = (string) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskSizeGb")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskSizeGb = (long) content.GetValueForProperty("DiskSizeGb",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskSizeGb, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskFileFormat")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskFileFormat = (string) content.GetValueForProperty("DiskFileFormat",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskFileFormat, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsOSDisk = (bool) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskPhysicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskIdentifier")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskIdentifier = (string) content.GetValueForProperty("DiskIdentifier",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskIdentifier, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerName = (string) content.GetValueForProperty("DiskControllerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerName, global::System.Convert.ToString); + } + if (content.Contains("DiskControllerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerId = (int?) content.GetValueForProperty("DiskControllerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("DiskControllerLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerLocation = (int?) content.GetValueForProperty("DiskControllerLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal)this).DiskControllerLocation, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializePSObject(content); + } + } + /// VMwareToAzStack disk input. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcidiskInputTypeConverter))] + public partial interface IVMwareToAzStackHcidiskInput + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.TypeConverter.cs new file mode 100644 index 00000000000..ed8f716e609 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHcidiskInputTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHcidiskInput.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHcidiskInput.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHcidiskInput.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.cs new file mode 100644 index 00000000000..5fe77a363a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.cs @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStack disk input. + public partial class VMwareToAzStackHcidiskInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal + { + + /// Backing field for property. + private long? _diskBlockSize; + + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskBlockSize { get => this._diskBlockSize; set => this._diskBlockSize = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs _diskController; + + /// Disk controller. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs DiskController { get => (this._diskController = this._diskController ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputs()); set => this._diskController = value; } + + /// Gets or sets the controller ID. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DiskControllerId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerId = value ?? default(int); } + + /// Gets or sets the controller Location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DiskControllerLocation { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerLocation; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerLocation = value ?? default(int); } + + /// Gets or sets the controller name (IDE,SCSI). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string DiskControllerName { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerName; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputsInternal)DiskController).ControllerName = value ?? null; } + + /// Backing field for property. + private string _diskFileFormat; + + /// Gets or sets the type of the virtual hard disk, vhd or vhdx. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskFileFormat { get => this._diskFileFormat; set => this._diskFileFormat = value; } + + /// Backing field for property. + private string _diskId; + + /// Gets or sets the disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskId { get => this._diskId; set => this._diskId = value; } + + /// Backing field for property. + private string _diskIdentifier; + + /// Gets or sets a value of disk identifier. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskIdentifier { get => this._diskIdentifier; set => this._diskIdentifier = value; } + + /// Backing field for property. + private long? _diskLogicalSectorSize; + + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskLogicalSectorSize { get => this._diskLogicalSectorSize; set => this._diskLogicalSectorSize = value; } + + /// Backing field for property. + private long? _diskPhysicalSectorSize; + + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskPhysicalSectorSize { get => this._diskPhysicalSectorSize; set => this._diskPhysicalSectorSize = value; } + + /// Backing field for property. + private long _diskSizeGb; + + /// Gets or sets the disk size in GB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long DiskSizeGb { get => this._diskSizeGb; set => this._diskSizeGb = value; } + + /// Backing field for property. + private bool? _isDynamic; + + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamic { get => this._isDynamic; set => this._isDynamic = value; } + + /// Backing field for property. + private bool _isOSDisk; + + /// Gets or sets a value indicating whether disk is os disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool IsOSDisk { get => this._isOSDisk; set => this._isOSDisk = value; } + + /// Internal Acessors for DiskController + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInputInternal.DiskController { get => (this._diskController = this._diskController ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputs()); set { {_diskController = value;} } } + + /// Backing field for property. + private string _storageContainerId; + + /// Gets or sets the target storage account ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerId { get => this._storageContainerId; set => this._storageContainerId = value; } + + /// Creates an new instance. + public VMwareToAzStackHcidiskInput() + { + + } + } + /// VMwareToAzStack disk input. + public partial interface IVMwareToAzStackHcidiskInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk block size.", + SerializedName = @"diskBlockSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskBlockSize { get; set; } + /// Gets or sets the controller ID. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller ID.", + SerializedName = @"controllerId", + PossibleTypes = new [] { typeof(int) })] + int? DiskControllerId { get; set; } + /// Gets or sets the controller Location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller Location.", + SerializedName = @"controllerLocation", + PossibleTypes = new [] { typeof(int) })] + int? DiskControllerLocation { get; set; } + /// Gets or sets the controller name (IDE,SCSI). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the controller name (IDE,SCSI).", + SerializedName = @"controllerName", + PossibleTypes = new [] { typeof(string) })] + string DiskControllerName { get; set; } + /// Gets or sets the type of the virtual hard disk, vhd or vhdx. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of the virtual hard disk, vhd or vhdx.", + SerializedName = @"diskFileFormat", + PossibleTypes = new [] { typeof(string) })] + string DiskFileFormat { get; set; } + /// Gets or sets the disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the disk Id.", + SerializedName = @"diskId", + PossibleTypes = new [] { typeof(string) })] + string DiskId { get; set; } + /// Gets or sets a value of disk identifier. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk identifier.", + SerializedName = @"diskIdentifier", + PossibleTypes = new [] { typeof(string) })] + string DiskIdentifier { get; set; } + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk logical sector size.", + SerializedName = @"diskLogicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskLogicalSectorSize { get; set; } + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value of disk physical sector size.", + SerializedName = @"diskPhysicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskPhysicalSectorSize { get; set; } + /// Gets or sets the disk size in GB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the disk size in GB.", + SerializedName = @"diskSizeGB", + PossibleTypes = new [] { typeof(long) })] + long DiskSizeGb { get; set; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk.", + SerializedName = @"isDynamic", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamic { get; set; } + /// Gets or sets a value indicating whether disk is os disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether disk is os disk.", + SerializedName = @"isOsDisk", + PossibleTypes = new [] { typeof(bool) })] + bool IsOSDisk { get; set; } + /// Gets or sets the target storage account ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target storage account ARM Id.", + SerializedName = @"storageContainerId", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerId { get; set; } + + } + /// VMwareToAzStack disk input. + internal partial interface IVMwareToAzStackHcidiskInputInternal + + { + /// Gets or sets a value of disk block size. + long? DiskBlockSize { get; set; } + /// Disk controller. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDiskControllerInputs DiskController { get; set; } + /// Gets or sets the controller ID. + int? DiskControllerId { get; set; } + /// Gets or sets the controller Location. + int? DiskControllerLocation { get; set; } + /// Gets or sets the controller name (IDE,SCSI). + string DiskControllerName { get; set; } + /// Gets or sets the type of the virtual hard disk, vhd or vhdx. + string DiskFileFormat { get; set; } + /// Gets or sets the disk Id. + string DiskId { get; set; } + /// Gets or sets a value of disk identifier. + string DiskIdentifier { get; set; } + /// Gets or sets a value of disk logical sector size. + long? DiskLogicalSectorSize { get; set; } + /// Gets or sets a value of disk physical sector size. + long? DiskPhysicalSectorSize { get; set; } + /// Gets or sets the disk size in GB. + long DiskSizeGb { get; set; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + bool? IsDynamic { get; set; } + /// Gets or sets a value indicating whether disk is os disk. + bool IsOSDisk { get; set; } + /// Gets or sets the target storage account ARM Id. + string StorageContainerId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.json.cs new file mode 100644 index 00000000000..d2192c2c640 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcidiskInput.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStack disk input. + public partial class VMwareToAzStackHcidiskInput + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHcidiskInput(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._diskController ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._diskController.ToJson(null,serializationMode) : null, "diskController" ,container.Add ); + AddIf( null != (((object)this._diskId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskId.ToString()) : null, "diskId" ,container.Add ); + AddIf( null != (((object)this._storageContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerId.ToString()) : null, "storageContainerId" ,container.Add ); + AddIf( null != this._isDynamic ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamic) : null, "isDynamic" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._diskSizeGb), "diskSizeGB" ,container.Add ); + AddIf( null != (((object)this._diskFileFormat)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskFileFormat.ToString()) : null, "diskFileFormat" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean(this._isOSDisk), "isOsDisk" ,container.Add ); + AddIf( null != this._diskBlockSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskBlockSize) : null, "diskBlockSize" ,container.Add ); + AddIf( null != this._diskLogicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskLogicalSectorSize) : null, "diskLogicalSectorSize" ,container.Add ); + AddIf( null != this._diskPhysicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskPhysicalSectorSize) : null, "diskPhysicalSectorSize" ,container.Add ); + AddIf( null != (((object)this._diskIdentifier)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskIdentifier.ToString()) : null, "diskIdentifier" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHcidiskInput(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_diskController = If( json?.PropertyT("diskController"), out var __jsonDiskController) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DiskControllerInputs.FromJson(__jsonDiskController) : _diskController;} + {_diskId = If( json?.PropertyT("diskId"), out var __jsonDiskId) ? (string)__jsonDiskId : (string)_diskId;} + {_storageContainerId = If( json?.PropertyT("storageContainerId"), out var __jsonStorageContainerId) ? (string)__jsonStorageContainerId : (string)_storageContainerId;} + {_isDynamic = If( json?.PropertyT("isDynamic"), out var __jsonIsDynamic) ? (bool?)__jsonIsDynamic : _isDynamic;} + {_diskSizeGb = If( json?.PropertyT("diskSizeGB"), out var __jsonDiskSizeGb) ? (long)__jsonDiskSizeGb : _diskSizeGb;} + {_diskFileFormat = If( json?.PropertyT("diskFileFormat"), out var __jsonDiskFileFormat) ? (string)__jsonDiskFileFormat : (string)_diskFileFormat;} + {_isOSDisk = If( json?.PropertyT("isOsDisk"), out var __jsonIsOSDisk) ? (bool)__jsonIsOSDisk : _isOSDisk;} + {_diskBlockSize = If( json?.PropertyT("diskBlockSize"), out var __jsonDiskBlockSize) ? (long?)__jsonDiskBlockSize : _diskBlockSize;} + {_diskLogicalSectorSize = If( json?.PropertyT("diskLogicalSectorSize"), out var __jsonDiskLogicalSectorSize) ? (long?)__jsonDiskLogicalSectorSize : _diskLogicalSectorSize;} + {_diskPhysicalSectorSize = If( json?.PropertyT("diskPhysicalSectorSize"), out var __jsonDiskPhysicalSectorSize) ? (long?)__jsonDiskPhysicalSectorSize : _diskPhysicalSectorSize;} + {_diskIdentifier = If( json?.PropertyT("diskIdentifier"), out var __jsonDiskIdentifier) ? (string)__jsonDiskIdentifier : (string)_diskIdentifier;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..f4495c1e698 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.PowerShell.cs @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + /// + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcieventModelCustomPropertiesTypeConverter))] + public partial class VMwareToAzStackHcieventModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHcieventModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHcieventModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHcieventModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("EventSourceFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName = (string) content.GetValueForProperty("EventSourceFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("ProtectedItemFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName = (string) content.GetValueForProperty("ProtectedItemFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("ServerType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ServerType = (string) content.GetValueForProperty("ServerType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ServerType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType, 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 VMwareToAzStackHcieventModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("EventSourceFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName = (string) content.GetValueForProperty("EventSourceFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).EventSourceFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("ProtectedItemFriendlyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName = (string) content.GetValueForProperty("ProtectedItemFriendlyName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ProtectedItemFriendlyName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("ServerType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ServerType = (string) content.GetValueForProperty("ServerType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal)this).ServerType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcieventModelCustomPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHcieventModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..e9404b49e0e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHcieventModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHcieventModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHcieventModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHcieventModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.cs new file mode 100644 index 00000000000..aa330d6bfd6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + /// + public partial class VMwareToAzStackHcieventModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties __eventModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties(); + + /// Backing field for property. + private string _eventSourceFriendlyName; + + /// + /// Gets or sets the friendly name of the source which has raised this health event. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string EventSourceFriendlyName { get => this._eventSourceFriendlyName; } + + /// Discriminator property for EventModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal)__eventModelCustomProperties).InstanceType = "VMwareToAzStackHCI"; } + + /// Internal Acessors for EventSourceFriendlyName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal.EventSourceFriendlyName { get => this._eventSourceFriendlyName; set { {_eventSourceFriendlyName = value;} } } + + /// Internal Acessors for ProtectedItemFriendlyName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal.ProtectedItemFriendlyName { get => this._protectedItemFriendlyName; set { {_protectedItemFriendlyName = value;} } } + + /// Internal Acessors for ServerType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal.ServerType { get => this._serverType; set { {_serverType = value;} } } + + /// Internal Acessors for SourceApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal.SourceApplianceName { get => this._sourceApplianceName; set { {_sourceApplianceName = value;} } } + + /// Internal Acessors for TargetApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomPropertiesInternal.TargetApplianceName { get => this._targetApplianceName; set { {_targetApplianceName = value;} } } + + /// Backing field for property. + private string _protectedItemFriendlyName; + + /// Gets or sets the protected item friendly name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProtectedItemFriendlyName { get => this._protectedItemFriendlyName; } + + /// Backing field for property. + private string _serverType; + + /// Gets or sets the server type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ServerType { get => this._serverType; } + + /// Backing field for property. + private string _sourceApplianceName; + + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceApplianceName { get => this._sourceApplianceName; } + + /// Backing field for property. + private string _targetApplianceName; + + /// Gets or sets the source target name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetApplianceName { get => this._targetApplianceName; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHcieventModelCustomProperties() + { + this.__eventModelCustomProperties.InstanceType = "VMwareToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__eventModelCustomProperties), __eventModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__eventModelCustomProperties), __eventModelCustomProperties); + } + } + /// VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + public partial interface IVMwareToAzStackHcieventModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomProperties + { + /// + /// Gets or sets the friendly name of the source which has raised this health event. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the friendly name of the source which has raised this health event.", + SerializedName = @"eventSourceFriendlyName", + PossibleTypes = new [] { typeof(string) })] + string EventSourceFriendlyName { get; } + /// Gets or sets the protected item friendly name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the protected item friendly name.", + SerializedName = @"protectedItemFriendlyName", + PossibleTypes = new [] { typeof(string) })] + string ProtectedItemFriendlyName { get; } + /// Gets or sets the server type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the server type.", + SerializedName = @"serverType", + PossibleTypes = new [] { typeof(string) })] + string ServerType { get; } + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source appliance name.", + SerializedName = @"sourceApplianceName", + PossibleTypes = new [] { typeof(string) })] + string SourceApplianceName { get; } + /// Gets or sets the source target name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source target name.", + SerializedName = @"targetApplianceName", + PossibleTypes = new [] { typeof(string) })] + string TargetApplianceName { get; } + + } + /// VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + internal partial interface IVMwareToAzStackHcieventModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModelCustomPropertiesInternal + { + /// + /// Gets or sets the friendly name of the source which has raised this health event. + /// + string EventSourceFriendlyName { get; set; } + /// Gets or sets the protected item friendly name. + string ProtectedItemFriendlyName { get; set; } + /// Gets or sets the server type. + string ServerType { get; set; } + /// Gets or sets the source appliance name. + string SourceApplianceName { get; set; } + /// Gets or sets the source target name. + string TargetApplianceName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.json.cs new file mode 100644 index 00000000000..8d2e56165a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcieventModelCustomProperties.json.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// VMware to AzStackHCI event model custom properties. This class provides provider specific details for events of type DataContract.HealthEvents.HealthEventType.ProtectedItemHealth + /// and DataContract.HealthEvents.HealthEventType.AgentHealth. + /// + public partial class VMwareToAzStackHcieventModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcieventModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHcieventModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __eventModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eventSourceFriendlyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._eventSourceFriendlyName.ToString()) : null, "eventSourceFriendlyName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._protectedItemFriendlyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._protectedItemFriendlyName.ToString()) : null, "protectedItemFriendlyName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceApplianceName.ToString()) : null, "sourceApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetApplianceName.ToString()) : null, "targetApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._serverType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._serverType.ToString()) : null, "serverType" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHcieventModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __eventModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EventModelCustomProperties(json); + {_eventSourceFriendlyName = If( json?.PropertyT("eventSourceFriendlyName"), out var __jsonEventSourceFriendlyName) ? (string)__jsonEventSourceFriendlyName : (string)_eventSourceFriendlyName;} + {_protectedItemFriendlyName = If( json?.PropertyT("protectedItemFriendlyName"), out var __jsonProtectedItemFriendlyName) ? (string)__jsonProtectedItemFriendlyName : (string)_protectedItemFriendlyName;} + {_sourceApplianceName = If( json?.PropertyT("sourceApplianceName"), out var __jsonSourceApplianceName) ? (string)__jsonSourceApplianceName : (string)_sourceApplianceName;} + {_targetApplianceName = If( json?.PropertyT("targetApplianceName"), out var __jsonTargetApplianceName) ? (string)__jsonTargetApplianceName : (string)_targetApplianceName;} + {_serverType = If( json?.PropertyT("serverType"), out var __jsonServerType) ? (string)__jsonServerType : (string)_serverType;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.PowerShell.cs new file mode 100644 index 00000000000..bc84b71c6cd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.PowerShell.cs @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMwareToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcinicInputTypeConverter))] + public partial class VMwareToAzStackHcinicInput + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHcinicInput(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHcinicInput(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHcinicInput(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).Label, global::System.Convert.ToString); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).SelectionTypeForFailover, global::System.Convert.ToString); + } + if (content.Contains("IsStaticIPMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled = (bool?) content.GetValueForProperty("IsStaticIPMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("IsMacMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsMacMigrationEnabled = (bool?) content.GetValueForProperty("IsMacMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsMacMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VMwareToAzStackHcinicInput(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).Label, global::System.Convert.ToString); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).SelectionTypeForFailover, global::System.Convert.ToString); + } + if (content.Contains("IsStaticIPMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled = (bool?) content.GetValueForProperty("IsStaticIPMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsStaticIPMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("IsMacMigrationEnabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsMacMigrationEnabled = (bool?) content.GetValueForProperty("IsMacMigrationEnabled",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal)this).IsMacMigrationEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + AfterDeserializePSObject(content); + } + } + /// VMwareToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcinicInputTypeConverter))] + public partial interface IVMwareToAzStackHcinicInput + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.TypeConverter.cs new file mode 100644 index 00000000000..ac6248d3d26 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHcinicInputTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHcinicInput.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHcinicInput.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHcinicInput.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.cs new file mode 100644 index 00000000000..4ecf11b850c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStackHCI NIC properties. + public partial class VMwareToAzStackHcinicInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal + { + + /// Backing field for property. + private bool? _isMacMigrationEnabled; + + /// Gets or sets a value indicating whether mac address migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsMacMigrationEnabled { get => this._isMacMigrationEnabled; set => this._isMacMigrationEnabled = value; } + + /// Backing field for property. + private bool? _isStaticIPMigrationEnabled; + + /// Gets or sets a value indicating whether static ip migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsStaticIPMigrationEnabled { get => this._isStaticIPMigrationEnabled; set => this._isStaticIPMigrationEnabled = value; } + + /// Backing field for property. + private string _label; + + /// Gets or sets the NIC label. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Label { get => this._label; set => this._label = value; } + + /// Internal Acessors for NetworkName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInputInternal.NetworkName { get => this._networkName; set { {_networkName = value;} } } + + /// Backing field for property. + private string _networkName; + + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NetworkName { get => this._networkName; } + + /// Backing field for property. + private string _nicId; + + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NicId { get => this._nicId; set => this._nicId = value; } + + /// Backing field for property. + private string _selectionTypeForFailover; + + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SelectionTypeForFailover { get => this._selectionTypeForFailover; set => this._selectionTypeForFailover = value; } + + /// Backing field for property. + private string _targetNetworkId; + + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetNetworkId { get => this._targetNetworkId; set => this._targetNetworkId = value; } + + /// Backing field for property. + private string _testNetworkId; + + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestNetworkId { get => this._testNetworkId; set => this._testNetworkId = value; } + + /// Creates an new instance. + public VMwareToAzStackHcinicInput() + { + + } + } + /// VMwareToAzStackHCI NIC properties. + public partial interface IVMwareToAzStackHcinicInput : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets a value indicating whether mac address migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether mac address migration is enabled.", + SerializedName = @"isMacMigrationEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? IsMacMigrationEnabled { get; set; } + /// Gets or sets a value indicating whether static ip migration is enabled. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether static ip migration is enabled.", + SerializedName = @"isStaticIpMigrationEnabled", + PossibleTypes = new [] { typeof(bool) })] + bool? IsStaticIPMigrationEnabled { get; set; } + /// Gets or sets the NIC label. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the NIC label.", + SerializedName = @"label", + PossibleTypes = new [] { typeof(string) })] + string Label { get; set; } + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the network name.", + SerializedName = @"networkName", + PossibleTypes = new [] { typeof(string) })] + string NetworkName { get; } + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the NIC Id.", + SerializedName = @"nicId", + PossibleTypes = new [] { typeof(string) })] + string NicId { get; set; } + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the selection type of the NIC.", + SerializedName = @"selectionTypeForFailover", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target network Id within AzStackHCI Cluster.", + SerializedName = @"targetNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TargetNetworkId { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target test network Id within AzStackHCI Cluster.", + SerializedName = @"testNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TestNetworkId { get; set; } + + } + /// VMwareToAzStackHCI NIC properties. + internal partial interface IVMwareToAzStackHcinicInputInternal + + { + /// Gets or sets a value indicating whether mac address migration is enabled. + bool? IsMacMigrationEnabled { get; set; } + /// Gets or sets a value indicating whether static ip migration is enabled. + bool? IsStaticIPMigrationEnabled { get; set; } + /// Gets or sets the NIC label. + string Label { get; set; } + /// Gets or sets the network name. + string NetworkName { get; set; } + /// Gets or sets the NIC Id. + string NicId { get; set; } + /// Gets or sets the selection type of the NIC. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + string TargetNetworkId { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + string TestNetworkId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.json.cs new file mode 100644 index 00000000000..54845e8996e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcinicInput.json.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStackHCI NIC properties. + public partial class VMwareToAzStackHcinicInput + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHcinicInput(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nicId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._nicId.ToString()) : null, "nicId" ,container.Add ); + AddIf( null != (((object)this._label)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._label.ToString()) : null, "label" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._networkName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._networkName.ToString()) : null, "networkName" ,container.Add ); + } + AddIf( null != (((object)this._targetNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetNetworkId.ToString()) : null, "targetNetworkId" ,container.Add ); + AddIf( null != (((object)this._testNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testNetworkId.ToString()) : null, "testNetworkId" ,container.Add ); + AddIf( null != (((object)this._selectionTypeForFailover)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._selectionTypeForFailover.ToString()) : null, "selectionTypeForFailover" ,container.Add ); + AddIf( null != this._isStaticIPMigrationEnabled ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isStaticIPMigrationEnabled) : null, "isStaticIpMigrationEnabled" ,container.Add ); + AddIf( null != this._isMacMigrationEnabled ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isMacMigrationEnabled) : null, "isMacMigrationEnabled" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHcinicInput(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nicId = If( json?.PropertyT("nicId"), out var __jsonNicId) ? (string)__jsonNicId : (string)_nicId;} + {_label = If( json?.PropertyT("label"), out var __jsonLabel) ? (string)__jsonLabel : (string)_label;} + {_networkName = If( json?.PropertyT("networkName"), out var __jsonNetworkName) ? (string)__jsonNetworkName : (string)_networkName;} + {_targetNetworkId = If( json?.PropertyT("targetNetworkId"), out var __jsonTargetNetworkId) ? (string)__jsonTargetNetworkId : (string)_targetNetworkId;} + {_testNetworkId = If( json?.PropertyT("testNetworkId"), out var __jsonTestNetworkId) ? (string)__jsonTestNetworkId : (string)_testNetworkId;} + {_selectionTypeForFailover = If( json?.PropertyT("selectionTypeForFailover"), out var __jsonSelectionTypeForFailover) ? (string)__jsonSelectionTypeForFailover : (string)_selectionTypeForFailover;} + {_isStaticIPMigrationEnabled = If( json?.PropertyT("isStaticIpMigrationEnabled"), out var __jsonIsStaticIPMigrationEnabled) ? (bool?)__jsonIsStaticIPMigrationEnabled : _isStaticIPMigrationEnabled;} + {_isMacMigrationEnabled = If( json?.PropertyT("isMacMigrationEnabled"), out var __jsonIsMacMigrationEnabled) ? (bool?)__jsonIsMacMigrationEnabled : _isMacMigrationEnabled;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..393c115c1ba --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware to AzStackHCI planned failover model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciplannedFailoverModelCustomPropertiesTypeConverter))] + public partial class VMwareToAzStackHciplannedFailoverModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHciplannedFailoverModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHciplannedFailoverModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHciplannedFailoverModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ShutdownSourceVM")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM = (bool) content.GetValueForProperty("ShutdownSourceVM",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType, 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 VMwareToAzStackHciplannedFailoverModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ShutdownSourceVM")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM = (bool) content.GetValueForProperty("ShutdownSourceVM",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomPropertiesInternal)this).ShutdownSourceVM, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware to AzStackHCI planned failover model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciplannedFailoverModelCustomPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHciplannedFailoverModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..d2d1b17d88d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHciplannedFailoverModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHciplannedFailoverModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHciplannedFailoverModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHciplannedFailoverModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.cs new file mode 100644 index 00000000000..9f807d0b756 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI planned failover model custom properties. + public partial class VMwareToAzStackHciplannedFailoverModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties __plannedFailoverModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties(); + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal)__plannedFailoverModelCustomProperties).InstanceType = "VMwareToAzStackHCI"; } + + /// Backing field for property. + private bool _shutdownSourceVM; + + /// Gets or sets a value indicating whether VM needs to be shut down. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool ShutdownSourceVM { get => this._shutdownSourceVM; set => this._shutdownSourceVM = value; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHciplannedFailoverModelCustomProperties() + { + this.__plannedFailoverModelCustomProperties.InstanceType = "VMwareToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__plannedFailoverModelCustomProperties), __plannedFailoverModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__plannedFailoverModelCustomProperties), __plannedFailoverModelCustomProperties); + } + } + /// VMware to AzStackHCI planned failover model custom properties. + public partial interface IVMwareToAzStackHciplannedFailoverModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomProperties + { + /// Gets or sets a value indicating whether VM needs to be shut down. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether VM needs to be shut down.", + SerializedName = @"shutdownSourceVM", + PossibleTypes = new [] { typeof(bool) })] + bool ShutdownSourceVM { get; set; } + + } + /// VMware to AzStackHCI planned failover model custom properties. + internal partial interface IVMwareToAzStackHciplannedFailoverModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModelCustomPropertiesInternal + { + /// Gets or sets a value indicating whether VM needs to be shut down. + bool ShutdownSourceVM { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.json.cs new file mode 100644 index 00000000000..7ad4b07f53a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciplannedFailoverModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI planned failover model custom properties. + public partial class VMwareToAzStackHciplannedFailoverModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciplannedFailoverModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHciplannedFailoverModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __plannedFailoverModelCustomProperties?.ToJson(container, serializationMode); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean(this._shutdownSourceVM), "shutdownSourceVM" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHciplannedFailoverModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __plannedFailoverModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModelCustomProperties(json); + {_shutdownSourceVM = If( json?.PropertyT("shutdownSourceVM"), out var __jsonShutdownSourceVM) ? (bool)__jsonShutdownSourceVM : _shutdownSourceVM;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..df8b71c180b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.PowerShell.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware To AzStackHCI Policy model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcipolicyModelCustomPropertiesTypeConverter))] + public partial class VMwareToAzStackHcipolicyModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHcipolicyModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHcipolicyModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHcipolicyModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RecoveryPointHistoryInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute = (int) content.GetValueForProperty("RecoveryPointHistoryInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("CrashConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute = (int) content.GetValueForProperty("CrashConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("AppConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute = (int) content.GetValueForProperty("AppConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType, 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 VMwareToAzStackHcipolicyModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RecoveryPointHistoryInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute = (int) content.GetValueForProperty("RecoveryPointHistoryInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).RecoveryPointHistoryInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("CrashConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute = (int) content.GetValueForProperty("CrashConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).CrashConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("AppConsistentFrequencyInMinute")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute = (int) content.GetValueForProperty("AppConsistentFrequencyInMinute",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal)this).AppConsistentFrequencyInMinute, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware To AzStackHCI Policy model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcipolicyModelCustomPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHcipolicyModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..aa9f8940c42 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHcipolicyModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHcipolicyModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHcipolicyModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHcipolicyModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.cs new file mode 100644 index 00000000000..b54e047367c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware To AzStackHCI Policy model custom properties. + public partial class VMwareToAzStackHcipolicyModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties __policyModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties(); + + /// Backing field for property. + private int _appConsistentFrequencyInMinute; + + /// Gets or sets the app consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int AppConsistentFrequencyInMinute { get => this._appConsistentFrequencyInMinute; set => this._appConsistentFrequencyInMinute = value; } + + /// Backing field for property. + private int _crashConsistentFrequencyInMinute; + + /// Gets or sets the crash consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int CrashConsistentFrequencyInMinute { get => this._crashConsistentFrequencyInMinute; set => this._crashConsistentFrequencyInMinute = value; } + + /// Discriminator property for PolicyModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal)__policyModelCustomProperties).InstanceType = "VMwareToAzStackHCI"; } + + /// Backing field for property. + private int _recoveryPointHistoryInMinute; + + /// + /// Gets or sets the duration in minutes until which the recovery points need to be stored. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int RecoveryPointHistoryInMinute { get => this._recoveryPointHistoryInMinute; set => this._recoveryPointHistoryInMinute = value; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHcipolicyModelCustomProperties() + { + this.__policyModelCustomProperties.InstanceType = "VMwareToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__policyModelCustomProperties), __policyModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__policyModelCustomProperties), __policyModelCustomProperties); + } + } + /// VMware To AzStackHCI Policy model custom properties. + public partial interface IVMwareToAzStackHcipolicyModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomProperties + { + /// Gets or sets the app consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the app consistent snapshot frequency (in minutes).", + SerializedName = @"appConsistentFrequencyInMinutes", + PossibleTypes = new [] { typeof(int) })] + int AppConsistentFrequencyInMinute { get; set; } + /// Gets or sets the crash consistent snapshot frequency (in minutes). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the crash consistent snapshot frequency (in minutes).", + SerializedName = @"crashConsistentFrequencyInMinutes", + PossibleTypes = new [] { typeof(int) })] + int CrashConsistentFrequencyInMinute { get; set; } + /// + /// Gets or sets the duration in minutes until which the recovery points need to be stored. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the duration in minutes until which the recovery points need to be stored.", + SerializedName = @"recoveryPointHistoryInMinutes", + PossibleTypes = new [] { typeof(int) })] + int RecoveryPointHistoryInMinute { get; set; } + + } + /// VMware To AzStackHCI Policy model custom properties. + internal partial interface IVMwareToAzStackHcipolicyModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModelCustomPropertiesInternal + { + /// Gets or sets the app consistent snapshot frequency (in minutes). + int AppConsistentFrequencyInMinute { get; set; } + /// Gets or sets the crash consistent snapshot frequency (in minutes). + int CrashConsistentFrequencyInMinute { get; set; } + /// + /// Gets or sets the duration in minutes until which the recovery points need to be stored. + /// + int RecoveryPointHistoryInMinute { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.json.cs new file mode 100644 index 00000000000..741398ea3fa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcipolicyModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware To AzStackHCI Policy model custom properties. + public partial class VMwareToAzStackHcipolicyModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcipolicyModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHcipolicyModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __policyModelCustomProperties?.ToJson(container, serializationMode); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._recoveryPointHistoryInMinute), "recoveryPointHistoryInMinutes" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._crashConsistentFrequencyInMinute), "crashConsistentFrequencyInMinutes" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber(this._appConsistentFrequencyInMinute), "appConsistentFrequencyInMinutes" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHcipolicyModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __policyModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModelCustomProperties(json); + {_recoveryPointHistoryInMinute = If( json?.PropertyT("recoveryPointHistoryInMinutes"), out var __jsonRecoveryPointHistoryInMinutes) ? (int)__jsonRecoveryPointHistoryInMinutes : _recoveryPointHistoryInMinute;} + {_crashConsistentFrequencyInMinute = If( json?.PropertyT("crashConsistentFrequencyInMinutes"), out var __jsonCrashConsistentFrequencyInMinutes) ? (int)__jsonCrashConsistentFrequencyInMinutes : _crashConsistentFrequencyInMinute;} + {_appConsistentFrequencyInMinute = If( json?.PropertyT("appConsistentFrequencyInMinutes"), out var __jsonAppConsistentFrequencyInMinutes) ? (int)__jsonAppConsistentFrequencyInMinutes : _appConsistentFrequencyInMinute;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.PowerShell.cs new file mode 100644 index 00000000000..e3626c659a9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.PowerShell.cs @@ -0,0 +1,271 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMwareToAzStackHCI protected disk properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedDiskPropertiesTypeConverter))] + public partial class VMwareToAzStackHciprotectedDiskProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHciprotectedDiskProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHciprotectedDiskProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHciprotectedDiskProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerLocalPath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath = (string) content.GetValueForProperty("StorageContainerLocalPath",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId = (string) content.GetValueForProperty("SourceDiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName = (string) content.GetValueForProperty("SourceDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName, global::System.Convert.ToString); + } + if (content.Contains("SeedDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName = (string) content.GetValueForProperty("SeedDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName, global::System.Convert.ToString); + } + if (content.Contains("TestMigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName = (string) content.GetValueForProperty("TestMigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("MigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName = (string) content.GetValueForProperty("MigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk = (bool?) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CapacityInByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte = (long?) content.GetValueForProperty("CapacityInByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskType = (string) content.GetValueForProperty("DiskType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskType, global::System.Convert.ToString); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize, (__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 VMwareToAzStackHciprotectedDiskProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerLocalPath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath = (string) content.GetValueForProperty("StorageContainerLocalPath",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).StorageContainerLocalPath, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId = (string) content.GetValueForProperty("SourceDiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskId, global::System.Convert.ToString); + } + if (content.Contains("SourceDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName = (string) content.GetValueForProperty("SourceDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SourceDiskName, global::System.Convert.ToString); + } + if (content.Contains("SeedDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName = (string) content.GetValueForProperty("SeedDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).SeedDiskName, global::System.Convert.ToString); + } + if (content.Contains("TestMigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName = (string) content.GetValueForProperty("TestMigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).TestMigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("MigrateDiskName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName = (string) content.GetValueForProperty("MigrateDiskName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).MigrateDiskName, global::System.Convert.ToString); + } + if (content.Contains("IsOSDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk = (bool?) content.GetValueForProperty("IsOSDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsOSDisk, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("CapacityInByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte = (long?) content.GetValueForProperty("CapacityInByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).CapacityInByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("IsDynamic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic = (bool?) content.GetValueForProperty("IsDynamic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).IsDynamic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("DiskType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskType = (string) content.GetValueForProperty("DiskType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskType, global::System.Convert.ToString); + } + if (content.Contains("DiskBlockSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize = (long?) content.GetValueForProperty("DiskBlockSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskBlockSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskLogicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize = (long?) content.GetValueForProperty("DiskLogicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskLogicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DiskPhysicalSectorSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize = (long?) content.GetValueForProperty("DiskPhysicalSectorSize",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal)this).DiskPhysicalSectorSize, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + AfterDeserializePSObject(content); + } + } + /// VMwareToAzStackHCI protected disk properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedDiskPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHciprotectedDiskProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.TypeConverter.cs new file mode 100644 index 00000000000..874c7dffc6d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHciprotectedDiskPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHciprotectedDiskProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedDiskProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedDiskProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.cs new file mode 100644 index 00000000000..ab922e507b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.cs @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStackHCI protected disk properties. + public partial class VMwareToAzStackHciprotectedDiskProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal + { + + /// Backing field for property. + private long? _capacityInByte; + + /// Gets or sets the disk capacity in bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? CapacityInByte { get => this._capacityInByte; } + + /// Backing field for property. + private long? _diskBlockSize; + + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskBlockSize { get => this._diskBlockSize; } + + /// Backing field for property. + private long? _diskLogicalSectorSize; + + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskLogicalSectorSize { get => this._diskLogicalSectorSize; } + + /// Backing field for property. + private long? _diskPhysicalSectorSize; + + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? DiskPhysicalSectorSize { get => this._diskPhysicalSectorSize; } + + /// Backing field for property. + private string _diskType; + + /// Gets or sets the disk type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string DiskType { get => this._diskType; } + + /// Backing field for property. + private bool? _isDynamic; + + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamic { get => this._isDynamic; } + + /// Backing field for property. + private bool? _isOSDisk; + + /// Gets or sets a value indicating whether the disk is the OS disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsOSDisk { get => this._isOSDisk; } + + /// Internal Acessors for CapacityInByte + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.CapacityInByte { get => this._capacityInByte; set { {_capacityInByte = value;} } } + + /// Internal Acessors for DiskBlockSize + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.DiskBlockSize { get => this._diskBlockSize; set { {_diskBlockSize = value;} } } + + /// Internal Acessors for DiskLogicalSectorSize + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.DiskLogicalSectorSize { get => this._diskLogicalSectorSize; set { {_diskLogicalSectorSize = value;} } } + + /// Internal Acessors for DiskPhysicalSectorSize + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.DiskPhysicalSectorSize { get => this._diskPhysicalSectorSize; set { {_diskPhysicalSectorSize = value;} } } + + /// Internal Acessors for DiskType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.DiskType { get => this._diskType; set { {_diskType = value;} } } + + /// Internal Acessors for IsDynamic + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.IsDynamic { get => this._isDynamic; set { {_isDynamic = value;} } } + + /// Internal Acessors for IsOSDisk + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.IsOSDisk { get => this._isOSDisk; set { {_isOSDisk = value;} } } + + /// Internal Acessors for MigrateDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.MigrateDiskName { get => this._migrateDiskName; set { {_migrateDiskName = value;} } } + + /// Internal Acessors for SeedDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.SeedDiskName { get => this._seedDiskName; set { {_seedDiskName = value;} } } + + /// Internal Acessors for SourceDiskId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.SourceDiskId { get => this._sourceDiskId; set { {_sourceDiskId = value;} } } + + /// Internal Acessors for SourceDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.SourceDiskName { get => this._sourceDiskName; set { {_sourceDiskName = value;} } } + + /// Internal Acessors for StorageContainerId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.StorageContainerId { get => this._storageContainerId; set { {_storageContainerId = value;} } } + + /// Internal Acessors for StorageContainerLocalPath + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.StorageContainerLocalPath { get => this._storageContainerLocalPath; set { {_storageContainerLocalPath = value;} } } + + /// Internal Acessors for TestMigrateDiskName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskPropertiesInternal.TestMigrateDiskName { get => this._testMigrateDiskName; set { {_testMigrateDiskName = value;} } } + + /// Backing field for property. + private string _migrateDiskName; + + /// Gets or sets the failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MigrateDiskName { get => this._migrateDiskName; } + + /// Backing field for property. + private string _seedDiskName; + + /// Gets or sets the seed disk name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SeedDiskName { get => this._seedDiskName; } + + /// Backing field for property. + private string _sourceDiskId; + + /// Gets or sets the source disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceDiskId { get => this._sourceDiskId; } + + /// Backing field for property. + private string _sourceDiskName; + + /// Gets or sets the source disk Name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceDiskName { get => this._sourceDiskName; } + + /// Backing field for property. + private string _storageContainerId; + + /// Gets or sets the ARM Id of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerId { get => this._storageContainerId; } + + /// Backing field for property. + private string _storageContainerLocalPath; + + /// Gets or sets the local path of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerLocalPath { get => this._storageContainerLocalPath; } + + /// Backing field for property. + private string _testMigrateDiskName; + + /// Gets or sets the test failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestMigrateDiskName { get => this._testMigrateDiskName; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHciprotectedDiskProperties() + { + + } + } + /// VMwareToAzStackHCI protected disk properties. + public partial interface IVMwareToAzStackHciprotectedDiskProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the disk capacity in bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the disk capacity in bytes.", + SerializedName = @"capacityInBytes", + PossibleTypes = new [] { typeof(long) })] + long? CapacityInByte { get; } + /// Gets or sets a value of disk block size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value of disk block size.", + SerializedName = @"diskBlockSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskBlockSize { get; } + /// Gets or sets a value of disk logical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value of disk logical sector size.", + SerializedName = @"diskLogicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskLogicalSectorSize { get; } + /// Gets or sets a value of disk physical sector size. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value of disk physical sector size.", + SerializedName = @"diskPhysicalSectorSize", + PossibleTypes = new [] { typeof(long) })] + long? DiskPhysicalSectorSize { get; } + /// Gets or sets the disk type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the disk type.", + SerializedName = @"diskType", + PossibleTypes = new [] { typeof(string) })] + string DiskType { get; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk.", + SerializedName = @"isDynamic", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamic { get; } + /// Gets or sets a value indicating whether the disk is the OS disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether the disk is the OS disk.", + SerializedName = @"isOsDisk", + PossibleTypes = new [] { typeof(bool) })] + bool? IsOSDisk { get; } + /// Gets or sets the failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the failover clone disk.", + SerializedName = @"migrateDiskName", + PossibleTypes = new [] { typeof(string) })] + string MigrateDiskName { get; } + /// Gets or sets the seed disk name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the seed disk name.", + SerializedName = @"seedDiskName", + PossibleTypes = new [] { typeof(string) })] + string SeedDiskName { get; } + /// Gets or sets the source disk Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source disk Id.", + SerializedName = @"sourceDiskId", + PossibleTypes = new [] { typeof(string) })] + string SourceDiskId { get; } + /// Gets or sets the source disk Name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source disk Name.", + SerializedName = @"sourceDiskName", + PossibleTypes = new [] { typeof(string) })] + string SourceDiskName { get; } + /// Gets or sets the ARM Id of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the ARM Id of the storage container.", + SerializedName = @"storageContainerId", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerId { get; } + /// Gets or sets the local path of the storage container. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the local path of the storage container.", + SerializedName = @"storageContainerLocalPath", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerLocalPath { get; } + /// Gets or sets the test failover clone disk. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the test failover clone disk.", + SerializedName = @"testMigrateDiskName", + PossibleTypes = new [] { typeof(string) })] + string TestMigrateDiskName { get; } + + } + /// VMwareToAzStackHCI protected disk properties. + internal partial interface IVMwareToAzStackHciprotectedDiskPropertiesInternal + + { + /// Gets or sets the disk capacity in bytes. + long? CapacityInByte { get; set; } + /// Gets or sets a value of disk block size. + long? DiskBlockSize { get; set; } + /// Gets or sets a value of disk logical sector size. + long? DiskLogicalSectorSize { get; set; } + /// Gets or sets a value of disk physical sector size. + long? DiskPhysicalSectorSize { get; set; } + /// Gets or sets the disk type. + string DiskType { get; set; } + /// + /// Gets or sets a value indicating whether dynamic sizing is enabled on the virtual hard disk. + /// + bool? IsDynamic { get; set; } + /// Gets or sets a value indicating whether the disk is the OS disk. + bool? IsOSDisk { get; set; } + /// Gets or sets the failover clone disk. + string MigrateDiskName { get; set; } + /// Gets or sets the seed disk name. + string SeedDiskName { get; set; } + /// Gets or sets the source disk Id. + string SourceDiskId { get; set; } + /// Gets or sets the source disk Name. + string SourceDiskName { get; set; } + /// Gets or sets the ARM Id of the storage container. + string StorageContainerId { get; set; } + /// Gets or sets the local path of the storage container. + string StorageContainerLocalPath { get; set; } + /// Gets or sets the test failover clone disk. + string TestMigrateDiskName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.json.cs new file mode 100644 index 00000000000..2e64d1988df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedDiskProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStackHCI protected disk properties. + public partial class VMwareToAzStackHciprotectedDiskProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHciprotectedDiskProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._storageContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerId.ToString()) : null, "storageContainerId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._storageContainerLocalPath)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerLocalPath.ToString()) : null, "storageContainerLocalPath" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceDiskId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceDiskId.ToString()) : null, "sourceDiskId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceDiskName.ToString()) : null, "sourceDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._seedDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._seedDiskName.ToString()) : null, "seedDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testMigrateDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testMigrateDiskName.ToString()) : null, "testMigrateDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._migrateDiskName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._migrateDiskName.ToString()) : null, "migrateDiskName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isOSDisk ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isOSDisk) : null, "isOsDisk" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._capacityInByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._capacityInByte) : null, "capacityInBytes" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDynamic ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamic) : null, "isDynamic" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._diskType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._diskType.ToString()) : null, "diskType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._diskBlockSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskBlockSize) : null, "diskBlockSize" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._diskLogicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskLogicalSectorSize) : null, "diskLogicalSectorSize" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._diskPhysicalSectorSize ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._diskPhysicalSectorSize) : null, "diskPhysicalSectorSize" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHciprotectedDiskProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_storageContainerId = If( json?.PropertyT("storageContainerId"), out var __jsonStorageContainerId) ? (string)__jsonStorageContainerId : (string)_storageContainerId;} + {_storageContainerLocalPath = If( json?.PropertyT("storageContainerLocalPath"), out var __jsonStorageContainerLocalPath) ? (string)__jsonStorageContainerLocalPath : (string)_storageContainerLocalPath;} + {_sourceDiskId = If( json?.PropertyT("sourceDiskId"), out var __jsonSourceDiskId) ? (string)__jsonSourceDiskId : (string)_sourceDiskId;} + {_sourceDiskName = If( json?.PropertyT("sourceDiskName"), out var __jsonSourceDiskName) ? (string)__jsonSourceDiskName : (string)_sourceDiskName;} + {_seedDiskName = If( json?.PropertyT("seedDiskName"), out var __jsonSeedDiskName) ? (string)__jsonSeedDiskName : (string)_seedDiskName;} + {_testMigrateDiskName = If( json?.PropertyT("testMigrateDiskName"), out var __jsonTestMigrateDiskName) ? (string)__jsonTestMigrateDiskName : (string)_testMigrateDiskName;} + {_migrateDiskName = If( json?.PropertyT("migrateDiskName"), out var __jsonMigrateDiskName) ? (string)__jsonMigrateDiskName : (string)_migrateDiskName;} + {_isOSDisk = If( json?.PropertyT("isOsDisk"), out var __jsonIsOSDisk) ? (bool?)__jsonIsOSDisk : _isOSDisk;} + {_capacityInByte = If( json?.PropertyT("capacityInBytes"), out var __jsonCapacityInBytes) ? (long?)__jsonCapacityInBytes : _capacityInByte;} + {_isDynamic = If( json?.PropertyT("isDynamic"), out var __jsonIsDynamic) ? (bool?)__jsonIsDynamic : _isDynamic;} + {_diskType = If( json?.PropertyT("diskType"), out var __jsonDiskType) ? (string)__jsonDiskType : (string)_diskType;} + {_diskBlockSize = If( json?.PropertyT("diskBlockSize"), out var __jsonDiskBlockSize) ? (long?)__jsonDiskBlockSize : _diskBlockSize;} + {_diskLogicalSectorSize = If( json?.PropertyT("diskLogicalSectorSize"), out var __jsonDiskLogicalSectorSize) ? (long?)__jsonDiskLogicalSectorSize : _diskLogicalSectorSize;} + {_diskPhysicalSectorSize = If( json?.PropertyT("diskPhysicalSectorSize"), out var __jsonDiskPhysicalSectorSize) ? (long?)__jsonDiskPhysicalSectorSize : _diskPhysicalSectorSize;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..9c1ad6b3750 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.PowerShell.cs @@ -0,0 +1,559 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedItemModelCustomPropertiesTypeConverter))] + public partial class VMwareToAzStackHciprotectedItemModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHciprotectedItemModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHciprotectedItemModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHciprotectedItemModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("ActiveLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation = (string) content.GetValueForProperty("ActiveLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation, global::System.Convert.ToString); + } + if (content.Contains("TargetHciClusterId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId = (string) content.GetValueForProperty("TargetHciClusterId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId, global::System.Convert.ToString); + } + if (content.Contains("TargetArcClusterCustomLocationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId = (string) content.GetValueForProperty("TargetArcClusterCustomLocationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId, global::System.Convert.ToString); + } + if (content.Contains("TargetAzStackHciClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName = (string) content.GetValueForProperty("TargetAzStackHciClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceGroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId = (string) content.GetValueForProperty("TargetResourceGroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId, global::System.Convert.ToString); + } + if (content.Contains("TargetLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation = (string) content.GetValueForProperty("TargetLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation, global::System.Convert.ToString); + } + if (content.Contains("CustomLocationRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion = (string) content.GetValueForProperty("CustomLocationRegion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion, global::System.Convert.ToString); + } + if (content.Contains("DisksToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude = (System.Collections.Generic.List) content.GetValueForProperty("DisksToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcidiskInputTypeConverter.ConvertFrom)); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("ProtectedDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHciprotectedDiskPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("ProtectedNic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedNic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHciprotectedNicPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetVMBiosId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId = (string) content.GetValueForProperty("TargetVMBiosId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId, global::System.Convert.ToString); + } + if (content.Contains("TargetVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName = (string) content.GetValueForProperty("TargetVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName, global::System.Convert.ToString); + } + if (content.Contains("HyperVGeneration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration = (string) content.GetValueForProperty("HyperVGeneration",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("OSName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName = (string) content.GetValueForProperty("OSName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName, global::System.Convert.ToString); + } + if (content.Contains("FirmwareType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType = (string) content.GetValueForProperty("FirmwareType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType, global::System.Convert.ToString); + } + if (content.Contains("FabricDiscoveryMachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId = (string) content.GetValueForProperty("FabricDiscoveryMachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId, global::System.Convert.ToString); + } + if (content.Contains("SourceVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName = (string) content.GetValueForProperty("SourceVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName, global::System.Convert.ToString); + } + if (content.Contains("SourceCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore = (int?) content.GetValueForProperty("SourceCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SourceMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte = (double?) content.GetValueForProperty("SourceMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte, (__y)=> (double) global::System.Convert.ChangeType(__y, typeof(double))); + } + if (content.Contains("RunAsAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId = (string) content.GetValueForProperty("RunAsAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName = (string) content.GetValueForProperty("SourceFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName = (string) content.GetValueForProperty("TargetFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("FailoverRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId = (string) content.GetValueForProperty("FailoverRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("LastRecoveryPointReceived")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived = (global::System.DateTime?) content.GetValueForProperty("LastRecoveryPointReceived",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId = (string) content.GetValueForProperty("LastRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("InitialReplicationProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage = (int?) content.GetValueForProperty("InitialReplicationProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("MigrationProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).MigrationProgressPercentage = (int?) content.GetValueForProperty("MigrationProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).MigrationProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResumeProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeProgressPercentage = (int?) content.GetValueForProperty("ResumeProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResyncProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage = (int?) content.GetValueForProperty("ResyncProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResyncRetryCount")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRetryCount = (long?) content.GetValueForProperty("ResyncRetryCount",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRetryCount, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("ResyncRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRequired = (bool?) content.GetValueForProperty("ResyncRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRequired, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ResyncState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncState = (string) content.GetValueForProperty("ResyncState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncState, global::System.Convert.ToString); + } + if (content.Contains("PerformAutoResync")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).PerformAutoResync = (bool?) content.GetValueForProperty("PerformAutoResync",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).PerformAutoResync, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ResumeRetryCount")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeRetryCount = (long?) content.GetValueForProperty("ResumeRetryCount",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeRetryCount, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("LastReplicationUpdateTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime = (global::System.DateTime?) content.GetValueForProperty("LastReplicationUpdateTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__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 VMwareToAzStackHciprotectedItemModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("ActiveLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation = (string) content.GetValueForProperty("ActiveLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ActiveLocation, global::System.Convert.ToString); + } + if (content.Contains("TargetHciClusterId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId = (string) content.GetValueForProperty("TargetHciClusterId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetHciClusterId, global::System.Convert.ToString); + } + if (content.Contains("TargetArcClusterCustomLocationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId = (string) content.GetValueForProperty("TargetArcClusterCustomLocationId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetArcClusterCustomLocationId, global::System.Convert.ToString); + } + if (content.Contains("TargetAzStackHciClusterName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName = (string) content.GetValueForProperty("TargetAzStackHciClusterName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetAzStackHciClusterName, global::System.Convert.ToString); + } + if (content.Contains("StorageContainerId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId = (string) content.GetValueForProperty("StorageContainerId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).StorageContainerId, global::System.Convert.ToString); + } + if (content.Contains("TargetResourceGroupId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId = (string) content.GetValueForProperty("TargetResourceGroupId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetResourceGroupId, global::System.Convert.ToString); + } + if (content.Contains("TargetLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation = (string) content.GetValueForProperty("TargetLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetLocation, global::System.Convert.ToString); + } + if (content.Contains("CustomLocationRegion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion = (string) content.GetValueForProperty("CustomLocationRegion",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).CustomLocationRegion, global::System.Convert.ToString); + } + if (content.Contains("DisksToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude = (System.Collections.Generic.List) content.GetValueForProperty("DisksToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DisksToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcidiskInputTypeConverter.ConvertFrom)); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("ProtectedDisk")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedDisk",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedDisk, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHciprotectedDiskPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("ProtectedNic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic = (System.Collections.Generic.List) content.GetValueForProperty("ProtectedNic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ProtectedNic, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHciprotectedNicPropertiesTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetVMBiosId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId = (string) content.GetValueForProperty("TargetVMBiosId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMBiosId, global::System.Convert.ToString); + } + if (content.Contains("TargetVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName = (string) content.GetValueForProperty("TargetVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetVMName, global::System.Convert.ToString); + } + if (content.Contains("HyperVGeneration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration = (string) content.GetValueForProperty("HyperVGeneration",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).HyperVGeneration, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("OSName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName = (string) content.GetValueForProperty("OSName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).OSName, global::System.Convert.ToString); + } + if (content.Contains("FirmwareType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType = (string) content.GetValueForProperty("FirmwareType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FirmwareType, global::System.Convert.ToString); + } + if (content.Contains("FabricDiscoveryMachineId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId = (string) content.GetValueForProperty("FabricDiscoveryMachineId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FabricDiscoveryMachineId, global::System.Convert.ToString); + } + if (content.Contains("SourceVMName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName = (string) content.GetValueForProperty("SourceVMName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceVMName, global::System.Convert.ToString); + } + if (content.Contains("SourceCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore = (int?) content.GetValueForProperty("SourceCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SourceMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte = (double?) content.GetValueForProperty("SourceMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceMemoryInMegaByte, (__y)=> (double) global::System.Convert.ChangeType(__y, typeof(double))); + } + if (content.Contains("RunAsAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId = (string) content.GetValueForProperty("RunAsAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).RunAsAccountId, global::System.Convert.ToString); + } + if (content.Contains("SourceFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName = (string) content.GetValueForProperty("SourceFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("TargetFabricAgentName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName = (string) content.GetValueForProperty("TargetFabricAgentName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetFabricAgentName, global::System.Convert.ToString); + } + if (content.Contains("SourceApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName = (string) content.GetValueForProperty("SourceApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).SourceApplianceName, global::System.Convert.ToString); + } + if (content.Contains("TargetApplianceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName = (string) content.GetValueForProperty("TargetApplianceName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).TargetApplianceName, global::System.Convert.ToString); + } + if (content.Contains("FailoverRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId = (string) content.GetValueForProperty("FailoverRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).FailoverRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("LastRecoveryPointReceived")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived = (global::System.DateTime?) content.GetValueForProperty("LastRecoveryPointReceived",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointReceived, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastRecoveryPointId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId = (string) content.GetValueForProperty("LastRecoveryPointId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastRecoveryPointId, global::System.Convert.ToString); + } + if (content.Contains("InitialReplicationProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage = (int?) content.GetValueForProperty("InitialReplicationProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).InitialReplicationProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("MigrationProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).MigrationProgressPercentage = (int?) content.GetValueForProperty("MigrationProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).MigrationProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResumeProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeProgressPercentage = (int?) content.GetValueForProperty("ResumeProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResyncProgressPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage = (int?) content.GetValueForProperty("ResyncProgressPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncProgressPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("ResyncRetryCount")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRetryCount = (long?) content.GetValueForProperty("ResyncRetryCount",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRetryCount, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("ResyncRequired")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRequired = (bool?) content.GetValueForProperty("ResyncRequired",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncRequired, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ResyncState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncState = (string) content.GetValueForProperty("ResyncState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResyncState, global::System.Convert.ToString); + } + if (content.Contains("PerformAutoResync")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).PerformAutoResync = (bool?) content.GetValueForProperty("PerformAutoResync",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).PerformAutoResync, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ResumeRetryCount")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeRetryCount = (long?) content.GetValueForProperty("ResumeRetryCount",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).ResumeRetryCount, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("LastReplicationUpdateTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime = (global::System.DateTime?) content.GetValueForProperty("LastReplicationUpdateTime",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).LastReplicationUpdateTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializePSObject(content); + } + } + /// VMware to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedItemModelCustomPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHciprotectedItemModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..2c79ea9643d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHciprotectedItemModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHciprotectedItemModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedItemModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedItemModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.cs new file mode 100644 index 00000000000..92b8d3db86f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.cs @@ -0,0 +1,1127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI Protected item model custom properties. + public partial class VMwareToAzStackHciprotectedItemModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties __protectedItemModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties(); + + /// Backing field for property. + private string _activeLocation; + + /// Gets or sets the location of the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ActiveLocation { get => this._activeLocation; } + + /// Backing field for property. + private string _customLocationRegion; + + /// Gets or sets the location of Azure Arc HCI custom location resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string CustomLocationRegion { get => this._customLocationRegion; set => this._customLocationRegion = value; } + + /// Backing field for property. + private System.Collections.Generic.List _disksToInclude; + + /// Gets or sets the list of disks to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List DisksToInclude { get => this._disksToInclude; set => this._disksToInclude = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig _dynamicMemoryConfig; + + /// Protected item dynamic memory config. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set => this._dynamicMemoryConfig = value; } + + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMaximumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMinimumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DynamicMemoryConfigTargetMemoryBufferPercentage { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage = value ?? default(int); } + + /// Backing field for property. + private string _fabricDiscoveryMachineId; + + /// Gets or sets the ARM Id of the discovered machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FabricDiscoveryMachineId { get => this._fabricDiscoveryMachineId; set => this._fabricDiscoveryMachineId = value; } + + /// Backing field for property. + private string _failoverRecoveryPointId; + + /// Gets or sets the recovery point Id to which the VM was failed over. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FailoverRecoveryPointId { get => this._failoverRecoveryPointId; } + + /// Backing field for property. + private string _firmwareType; + + /// Gets or sets the firmware type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string FirmwareType { get => this._firmwareType; } + + /// Backing field for property. + private string _hyperVGeneration; + + /// + /// Gets or sets the hypervisor generation of the virtual machine possible values are 1,2. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string HyperVGeneration { get => this._hyperVGeneration; set => this._hyperVGeneration = value; } + + /// Backing field for property. + private int? _initialReplicationProgressPercentage; + + /// + /// Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks + /// in the source VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? InitialReplicationProgressPercentage { get => this._initialReplicationProgressPercentage; } + + /// Discriminator property for ProtectedItemModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal)__protectedItemModelCustomProperties).InstanceType = "VMwareToAzStackHCI"; } + + /// Backing field for property. + private bool? _isDynamicRam; + + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamicRam { get => this._isDynamicRam; set => this._isDynamicRam = value; } + + /// Backing field for property. + private string _lastRecoveryPointId; + + /// Gets or sets the last recovery point Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string LastRecoveryPointId { get => this._lastRecoveryPointId; } + + /// Backing field for property. + private global::System.DateTime? _lastRecoveryPointReceived; + + /// Gets or sets the last recovery point received time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastRecoveryPointReceived { get => this._lastRecoveryPointReceived; } + + /// Backing field for property. + private global::System.DateTime? _lastReplicationUpdateTime; + + /// Gets or sets the latest timestamp that replication status is updated. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public global::System.DateTime? LastReplicationUpdateTime { get => this._lastReplicationUpdateTime; } + + /// Internal Acessors for ActiveLocation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ActiveLocation { get => this._activeLocation; set { {_activeLocation = value;} } } + + /// Internal Acessors for DynamicMemoryConfig + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set { {_dynamicMemoryConfig = value;} } } + + /// Internal Acessors for FailoverRecoveryPointId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.FailoverRecoveryPointId { get => this._failoverRecoveryPointId; set { {_failoverRecoveryPointId = value;} } } + + /// Internal Acessors for FirmwareType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.FirmwareType { get => this._firmwareType; set { {_firmwareType = value;} } } + + /// Internal Acessors for InitialReplicationProgressPercentage + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.InitialReplicationProgressPercentage { get => this._initialReplicationProgressPercentage; set { {_initialReplicationProgressPercentage = value;} } } + + /// Internal Acessors for LastRecoveryPointId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.LastRecoveryPointId { get => this._lastRecoveryPointId; set { {_lastRecoveryPointId = value;} } } + + /// Internal Acessors for LastRecoveryPointReceived + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.LastRecoveryPointReceived { get => this._lastRecoveryPointReceived; set { {_lastRecoveryPointReceived = value;} } } + + /// Internal Acessors for LastReplicationUpdateTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.LastReplicationUpdateTime { get => this._lastReplicationUpdateTime; set { {_lastReplicationUpdateTime = value;} } } + + /// Internal Acessors for MigrationProgressPercentage + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.MigrationProgressPercentage { get => this._migrationProgressPercentage; set { {_migrationProgressPercentage = value;} } } + + /// Internal Acessors for OSName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.OSName { get => this._oSName; set { {_oSName = value;} } } + + /// Internal Acessors for OSType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.OSType { get => this._oSType; set { {_oSType = value;} } } + + /// Internal Acessors for ProtectedDisk + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ProtectedDisk { get => this._protectedDisk; set { {_protectedDisk = value;} } } + + /// Internal Acessors for ProtectedNic + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ProtectedNic { get => this._protectedNic; set { {_protectedNic = value;} } } + + /// Internal Acessors for ResumeProgressPercentage + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ResumeProgressPercentage { get => this._resumeProgressPercentage; set { {_resumeProgressPercentage = value;} } } + + /// Internal Acessors for ResumeRetryCount + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ResumeRetryCount { get => this._resumeRetryCount; set { {_resumeRetryCount = value;} } } + + /// Internal Acessors for ResyncProgressPercentage + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ResyncProgressPercentage { get => this._resyncProgressPercentage; set { {_resyncProgressPercentage = value;} } } + + /// Internal Acessors for ResyncRequired + bool? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ResyncRequired { get => this._resyncRequired; set { {_resyncRequired = value;} } } + + /// Internal Acessors for ResyncRetryCount + long? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ResyncRetryCount { get => this._resyncRetryCount; set { {_resyncRetryCount = value;} } } + + /// Internal Acessors for ResyncState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.ResyncState { get => this._resyncState; set { {_resyncState = value;} } } + + /// Internal Acessors for SourceApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceApplianceName { get => this._sourceApplianceName; set { {_sourceApplianceName = value;} } } + + /// Internal Acessors for SourceCpuCore + int? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceCpuCore { get => this._sourceCpuCore; set { {_sourceCpuCore = value;} } } + + /// Internal Acessors for SourceMemoryInMegaByte + double? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceMemoryInMegaByte { get => this._sourceMemoryInMegaByte; set { {_sourceMemoryInMegaByte = value;} } } + + /// Internal Acessors for SourceVMName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.SourceVMName { get => this._sourceVMName; set { {_sourceVMName = value;} } } + + /// Internal Acessors for TargetApplianceName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetApplianceName { get => this._targetApplianceName; set { {_targetApplianceName = value;} } } + + /// Internal Acessors for TargetAzStackHciClusterName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetAzStackHciClusterName { get => this._targetAzStackHciClusterName; set { {_targetAzStackHciClusterName = value;} } } + + /// Internal Acessors for TargetLocation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetLocation { get => this._targetLocation; set { {_targetLocation = value;} } } + + /// Internal Acessors for TargetVMBiosId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal.TargetVMBiosId { get => this._targetVMBiosId; set { {_targetVMBiosId = value;} } } + + /// Backing field for property. + private int? _migrationProgressPercentage; + + /// Gets or sets the migration progress percentage. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? MigrationProgressPercentage { get => this._migrationProgressPercentage; } + + /// Backing field for property. + private System.Collections.Generic.List _nicsToInclude; + + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List NicsToInclude { get => this._nicsToInclude; set => this._nicsToInclude = value; } + + /// Backing field for property. + private string _oSName; + + /// Gets or sets the name of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OSName { get => this._oSName; } + + /// Backing field for property. + private string _oSType; + + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OSType { get => this._oSType; } + + /// Backing field for property. + private bool? _performAutoResync; + + /// Gets or sets a value indicating whether auto resync is to be done. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? PerformAutoResync { get => this._performAutoResync; set => this._performAutoResync = value; } + + /// Backing field for property. + private System.Collections.Generic.List _protectedDisk; + + /// Gets or sets the list of protected disks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ProtectedDisk { get => this._protectedDisk; } + + /// Backing field for property. + private System.Collections.Generic.List _protectedNic; + + /// Gets or sets the VM NIC details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List ProtectedNic { get => this._protectedNic; } + + /// Backing field for property. + private int? _resumeProgressPercentage; + + /// Gets or sets the resume progress percentage. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? ResumeProgressPercentage { get => this._resumeProgressPercentage; } + + /// Backing field for property. + private long? _resumeRetryCount; + + /// Gets or sets the resume retry count. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? ResumeRetryCount { get => this._resumeRetryCount; } + + /// Backing field for property. + private int? _resyncProgressPercentage; + + /// + /// Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source + /// VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? ResyncProgressPercentage { get => this._resyncProgressPercentage; } + + /// Backing field for property. + private bool? _resyncRequired; + + /// Gets or sets a value indicating whether resync is required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? ResyncRequired { get => this._resyncRequired; } + + /// Backing field for property. + private long? _resyncRetryCount; + + /// Gets or sets the resync retry count. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public long? ResyncRetryCount { get => this._resyncRetryCount; } + + /// Backing field for property. + private string _resyncState; + + /// Gets or sets the resync state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResyncState { get => this._resyncState; } + + /// Backing field for property. + private string _runAsAccountId; + + /// Gets or sets the run as account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RunAsAccountId { get => this._runAsAccountId; set => this._runAsAccountId = value; } + + /// Backing field for property. + private string _sourceApplianceName; + + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceApplianceName { get => this._sourceApplianceName; } + + /// Backing field for property. + private int? _sourceCpuCore; + + /// Gets or sets the source VM CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? SourceCpuCore { get => this._sourceCpuCore; } + + /// Backing field for property. + private string _sourceFabricAgentName; + + /// Gets or sets the source fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceFabricAgentName { get => this._sourceFabricAgentName; set => this._sourceFabricAgentName = value; } + + /// Backing field for property. + private double? _sourceMemoryInMegaByte; + + /// Gets or sets the source VM ram memory size in megabytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public double? SourceMemoryInMegaByte { get => this._sourceMemoryInMegaByte; } + + /// Backing field for property. + private string _sourceVMName; + + /// Gets or sets the source VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceVMName { get => this._sourceVMName; } + + /// Backing field for property. + private string _storageContainerId; + + /// Gets or sets the target storage container ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageContainerId { get => this._storageContainerId; set => this._storageContainerId = value; } + + /// Backing field for property. + private string _targetApplianceName; + + /// Gets or sets the target appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetApplianceName { get => this._targetApplianceName; } + + /// Backing field for property. + private string _targetArcClusterCustomLocationId; + + /// Gets or sets the Target Arc Cluster Custom Location ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetArcClusterCustomLocationId { get => this._targetArcClusterCustomLocationId; set => this._targetArcClusterCustomLocationId = value; } + + /// Backing field for property. + private string _targetAzStackHciClusterName; + + /// Gets or sets the Target AzStackHCI cluster name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetAzStackHciClusterName { get => this._targetAzStackHciClusterName; } + + /// Backing field for property. + private int? _targetCpuCore; + + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetCpuCore { get => this._targetCpuCore; set => this._targetCpuCore = value; } + + /// Backing field for property. + private string _targetFabricAgentName; + + /// Gets or sets the target fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetFabricAgentName { get => this._targetFabricAgentName; set => this._targetFabricAgentName = value; } + + /// Backing field for property. + private string _targetHciClusterId; + + /// Gets or sets the Target HCI Cluster ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetHciClusterId { get => this._targetHciClusterId; set => this._targetHciClusterId = value; } + + /// Backing field for property. + private string _targetLocation; + + /// Gets or sets the target location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetLocation { get => this._targetLocation; } + + /// Backing field for property. + private int? _targetMemoryInMegaByte; + + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetMemoryInMegaByte { get => this._targetMemoryInMegaByte; set => this._targetMemoryInMegaByte = value; } + + /// Backing field for property. + private string _targetNetworkId; + + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetNetworkId { get => this._targetNetworkId; set => this._targetNetworkId = value; } + + /// Backing field for property. + private string _targetResourceGroupId; + + /// Gets or sets the target resource group ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetResourceGroupId { get => this._targetResourceGroupId; set => this._targetResourceGroupId = value; } + + /// Backing field for property. + private string _targetVMBiosId; + + /// Gets or sets the BIOS Id of the target AzStackHCI VM. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetVMBiosId { get => this._targetVMBiosId; } + + /// Backing field for property. + private string _targetVMName; + + /// Gets or sets the target VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetVMName { get => this._targetVMName; set => this._targetVMName = value; } + + /// Backing field for property. + private string _testNetworkId; + + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestNetworkId { get => this._testNetworkId; set => this._testNetworkId = value; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHciprotectedItemModelCustomProperties() + { + this.__protectedItemModelCustomProperties.InstanceType = "VMwareToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__protectedItemModelCustomProperties), __protectedItemModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__protectedItemModelCustomProperties), __protectedItemModelCustomProperties); + } + } + /// VMware to AzStackHCI Protected item model custom properties. + public partial interface IVMwareToAzStackHciprotectedItemModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomProperties + { + /// Gets or sets the location of the protected item. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the location of the protected item.", + SerializedName = @"activeLocation", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Primary", "Recovery")] + string ActiveLocation { get; } + /// Gets or sets the location of Azure Arc HCI custom location resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the location of Azure Arc HCI custom location resource.", + SerializedName = @"customLocationRegion", + PossibleTypes = new [] { typeof(string) })] + string CustomLocationRegion { get; set; } + /// Gets or sets the list of disks to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of disks to replicate.", + SerializedName = @"disksToInclude", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput) })] + System.Collections.Generic.List DisksToInclude { get; set; } + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets maximum memory in MB.", + SerializedName = @"maximumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets minimum memory in MB.", + SerializedName = @"minimumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets target memory buffer in %.", + SerializedName = @"targetMemoryBufferPercentage", + PossibleTypes = new [] { typeof(int) })] + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets the ARM Id of the discovered machine. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the discovered machine.", + SerializedName = @"fabricDiscoveryMachineId", + PossibleTypes = new [] { typeof(string) })] + string FabricDiscoveryMachineId { get; set; } + /// Gets or sets the recovery point Id to which the VM was failed over. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the recovery point Id to which the VM was failed over.", + SerializedName = @"failoverRecoveryPointId", + PossibleTypes = new [] { typeof(string) })] + string FailoverRecoveryPointId { get; } + /// Gets or sets the firmware type. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the firmware type.", + SerializedName = @"firmwareType", + PossibleTypes = new [] { typeof(string) })] + string FirmwareType { get; } + /// + /// Gets or sets the hypervisor generation of the virtual machine possible values are 1,2. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the hypervisor generation of the virtual machine possible values are 1,2.", + SerializedName = @"hyperVGeneration", + PossibleTypes = new [] { typeof(string) })] + string HyperVGeneration { get; set; } + /// + /// Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks + /// in the source VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks in the source VM.", + SerializedName = @"initialReplicationProgressPercentage", + PossibleTypes = new [] { typeof(int) })] + int? InitialReplicationProgressPercentage { get; } + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether memory is dynamical.", + SerializedName = @"isDynamicRam", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamicRam { get; set; } + /// Gets or sets the last recovery point Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the last recovery point Id.", + SerializedName = @"lastRecoveryPointId", + PossibleTypes = new [] { typeof(string) })] + string LastRecoveryPointId { get; } + /// Gets or sets the last recovery point received time. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the last recovery point received time.", + SerializedName = @"lastRecoveryPointReceived", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastRecoveryPointReceived { get; } + /// Gets or sets the latest timestamp that replication status is updated. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the latest timestamp that replication status is updated.", + SerializedName = @"lastReplicationUpdateTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastReplicationUpdateTime { get; } + /// Gets or sets the migration progress percentage. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the migration progress percentage.", + SerializedName = @"migrationProgressPercentage", + PossibleTypes = new [] { typeof(int) })] + int? MigrationProgressPercentage { get; } + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of VM NIC to replicate.", + SerializedName = @"nicsToInclude", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput) })] + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the name of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the name of the OS.", + SerializedName = @"osName", + PossibleTypes = new [] { typeof(string) })] + string OSName { get; } + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the type of the OS.", + SerializedName = @"osType", + PossibleTypes = new [] { typeof(string) })] + string OSType { get; } + /// Gets or sets a value indicating whether auto resync is to be done. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether auto resync is to be done.", + SerializedName = @"performAutoResync", + PossibleTypes = new [] { typeof(bool) })] + bool? PerformAutoResync { get; set; } + /// Gets or sets the list of protected disks. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of protected disks.", + SerializedName = @"protectedDisks", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties) })] + System.Collections.Generic.List ProtectedDisk { get; } + /// Gets or sets the VM NIC details. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the VM NIC details.", + SerializedName = @"protectedNics", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties) })] + System.Collections.Generic.List ProtectedNic { get; } + /// Gets or sets the resume progress percentage. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resume progress percentage.", + SerializedName = @"resumeProgressPercentage", + PossibleTypes = new [] { typeof(int) })] + int? ResumeProgressPercentage { get; } + /// Gets or sets the resume retry count. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resume retry count.", + SerializedName = @"resumeRetryCount", + PossibleTypes = new [] { typeof(long) })] + long? ResumeRetryCount { get; } + /// + /// Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source + /// VM. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source VM.", + SerializedName = @"resyncProgressPercentage", + PossibleTypes = new [] { typeof(int) })] + int? ResyncProgressPercentage { get; } + /// Gets or sets a value indicating whether resync is required. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a value indicating whether resync is required.", + SerializedName = @"resyncRequired", + PossibleTypes = new [] { typeof(bool) })] + bool? ResyncRequired { get; } + /// Gets or sets the resync retry count. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resync retry count.", + SerializedName = @"resyncRetryCount", + PossibleTypes = new [] { typeof(long) })] + long? ResyncRetryCount { get; } + /// Gets or sets the resync state. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resync state.", + SerializedName = @"resyncState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "PreparedForResynchronization", "StartedResynchronization")] + string ResyncState { get; } + /// Gets or sets the run as account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the run as account Id.", + SerializedName = @"runAsAccountId", + PossibleTypes = new [] { typeof(string) })] + string RunAsAccountId { get; set; } + /// Gets or sets the source appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source appliance name.", + SerializedName = @"sourceApplianceName", + PossibleTypes = new [] { typeof(string) })] + string SourceApplianceName { get; } + /// Gets or sets the source VM CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source VM CPU cores.", + SerializedName = @"sourceCpuCores", + PossibleTypes = new [] { typeof(int) })] + int? SourceCpuCore { get; } + /// Gets or sets the source fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the source fabric agent name.", + SerializedName = @"sourceFabricAgentName", + PossibleTypes = new [] { typeof(string) })] + string SourceFabricAgentName { get; set; } + /// Gets or sets the source VM ram memory size in megabytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source VM ram memory size in megabytes.", + SerializedName = @"sourceMemoryInMegaBytes", + PossibleTypes = new [] { typeof(double) })] + double? SourceMemoryInMegaByte { get; } + /// Gets or sets the source VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source VM display name.", + SerializedName = @"sourceVmName", + PossibleTypes = new [] { typeof(string) })] + string SourceVMName { get; } + /// Gets or sets the target storage container ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target storage container ARM Id.", + SerializedName = @"storageContainerId", + PossibleTypes = new [] { typeof(string) })] + string StorageContainerId { get; set; } + /// Gets or sets the target appliance name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target appliance name.", + SerializedName = @"targetApplianceName", + PossibleTypes = new [] { typeof(string) })] + string TargetApplianceName { get; } + /// Gets or sets the Target Arc Cluster Custom Location ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Target Arc Cluster Custom Location ARM Id.", + SerializedName = @"targetArcClusterCustomLocationId", + PossibleTypes = new [] { typeof(string) })] + string TargetArcClusterCustomLocationId { get; set; } + /// Gets or sets the Target AzStackHCI cluster name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Target AzStackHCI cluster name.", + SerializedName = @"targetAzStackHciClusterName", + PossibleTypes = new [] { typeof(string) })] + string TargetAzStackHciClusterName { get; } + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target CPU cores.", + SerializedName = @"targetCpuCores", + PossibleTypes = new [] { typeof(int) })] + int? TargetCpuCore { get; set; } + /// Gets or sets the target fabric agent name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target fabric agent name.", + SerializedName = @"targetFabricAgentName", + PossibleTypes = new [] { typeof(string) })] + string TargetFabricAgentName { get; set; } + /// Gets or sets the Target HCI Cluster ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Target HCI Cluster ARM Id.", + SerializedName = @"targetHciClusterId", + PossibleTypes = new [] { typeof(string) })] + string TargetHciClusterId { get; set; } + /// Gets or sets the target location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target location.", + SerializedName = @"targetLocation", + PossibleTypes = new [] { typeof(string) })] + string TargetLocation { get; } + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target memory in mega-bytes.", + SerializedName = @"targetMemoryInMegaBytes", + PossibleTypes = new [] { typeof(int) })] + int? TargetMemoryInMegaByte { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target network Id within AzStackHCI Cluster.", + SerializedName = @"targetNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TargetNetworkId { get; set; } + /// Gets or sets the target resource group ARM Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target resource group ARM Id.", + SerializedName = @"targetResourceGroupId", + PossibleTypes = new [] { typeof(string) })] + string TargetResourceGroupId { get; set; } + /// Gets or sets the BIOS Id of the target AzStackHCI VM. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the BIOS Id of the target AzStackHCI VM.", + SerializedName = @"targetVmBiosId", + PossibleTypes = new [] { typeof(string) })] + string TargetVMBiosId { get; } + /// Gets or sets the target VM display name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target VM display name.", + SerializedName = @"targetVmName", + PossibleTypes = new [] { typeof(string) })] + string TargetVMName { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target test network Id within AzStackHCI Cluster.", + SerializedName = @"testNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TestNetworkId { get; set; } + + } + /// VMware to AzStackHCI Protected item model custom properties. + internal partial interface IVMwareToAzStackHciprotectedItemModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesInternal + { + /// Gets or sets the location of the protected item. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Primary", "Recovery")] + string ActiveLocation { get; set; } + /// Gets or sets the location of Azure Arc HCI custom location resource. + string CustomLocationRegion { get; set; } + /// Gets or sets the list of disks to replicate. + System.Collections.Generic.List DisksToInclude { get; set; } + /// Protected item dynamic memory config. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get; set; } + /// Gets or sets maximum memory in MB. + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets the ARM Id of the discovered machine. + string FabricDiscoveryMachineId { get; set; } + /// Gets or sets the recovery point Id to which the VM was failed over. + string FailoverRecoveryPointId { get; set; } + /// Gets or sets the firmware type. + string FirmwareType { get; set; } + /// + /// Gets or sets the hypervisor generation of the virtual machine possible values are 1,2. + /// + string HyperVGeneration { get; set; } + /// + /// Gets or sets the initial replication progress percentage. This is calculated based on total bytes processed for all disks + /// in the source VM. + /// + int? InitialReplicationProgressPercentage { get; set; } + /// Gets or sets a value indicating whether memory is dynamical. + bool? IsDynamicRam { get; set; } + /// Gets or sets the last recovery point Id. + string LastRecoveryPointId { get; set; } + /// Gets or sets the last recovery point received time. + global::System.DateTime? LastRecoveryPointReceived { get; set; } + /// Gets or sets the latest timestamp that replication status is updated. + global::System.DateTime? LastReplicationUpdateTime { get; set; } + /// Gets or sets the migration progress percentage. + int? MigrationProgressPercentage { get; set; } + /// Gets or sets the list of VM NIC to replicate. + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the name of the OS. + string OSName { get; set; } + /// Gets or sets the type of the OS. + string OSType { get; set; } + /// Gets or sets a value indicating whether auto resync is to be done. + bool? PerformAutoResync { get; set; } + /// Gets or sets the list of protected disks. + System.Collections.Generic.List ProtectedDisk { get; set; } + /// Gets or sets the VM NIC details. + System.Collections.Generic.List ProtectedNic { get; set; } + /// Gets or sets the resume progress percentage. + int? ResumeProgressPercentage { get; set; } + /// Gets or sets the resume retry count. + long? ResumeRetryCount { get; set; } + /// + /// Gets or sets the resync progress percentage. This is calculated based on total bytes processed for all disks in the source + /// VM. + /// + int? ResyncProgressPercentage { get; set; } + /// Gets or sets a value indicating whether resync is required. + bool? ResyncRequired { get; set; } + /// Gets or sets the resync retry count. + long? ResyncRetryCount { get; set; } + /// Gets or sets the resync state. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "PreparedForResynchronization", "StartedResynchronization")] + string ResyncState { get; set; } + /// Gets or sets the run as account Id. + string RunAsAccountId { get; set; } + /// Gets or sets the source appliance name. + string SourceApplianceName { get; set; } + /// Gets or sets the source VM CPU cores. + int? SourceCpuCore { get; set; } + /// Gets or sets the source fabric agent name. + string SourceFabricAgentName { get; set; } + /// Gets or sets the source VM ram memory size in megabytes. + double? SourceMemoryInMegaByte { get; set; } + /// Gets or sets the source VM display name. + string SourceVMName { get; set; } + /// Gets or sets the target storage container ARM Id. + string StorageContainerId { get; set; } + /// Gets or sets the target appliance name. + string TargetApplianceName { get; set; } + /// Gets or sets the Target Arc Cluster Custom Location ARM Id. + string TargetArcClusterCustomLocationId { get; set; } + /// Gets or sets the Target AzStackHCI cluster name. + string TargetAzStackHciClusterName { get; set; } + /// Gets or sets the target CPU cores. + int? TargetCpuCore { get; set; } + /// Gets or sets the target fabric agent name. + string TargetFabricAgentName { get; set; } + /// Gets or sets the Target HCI Cluster ARM Id. + string TargetHciClusterId { get; set; } + /// Gets or sets the target location. + string TargetLocation { get; set; } + /// Gets or sets the target memory in mega-bytes. + int? TargetMemoryInMegaByte { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + string TargetNetworkId { get; set; } + /// Gets or sets the target resource group ARM Id. + string TargetResourceGroupId { get; set; } + /// Gets or sets the BIOS Id of the target AzStackHCI VM. + string TargetVMBiosId { get; set; } + /// Gets or sets the target VM display name. + string TargetVMName { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + string TestNetworkId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.json.cs new file mode 100644 index 00000000000..3b639194926 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomProperties.json.cs @@ -0,0 +1,311 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI Protected item model custom properties. + public partial class VMwareToAzStackHciprotectedItemModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHciprotectedItemModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __protectedItemModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != this._dynamicMemoryConfig ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._dynamicMemoryConfig.ToJson(null,serializationMode) : null, "dynamicMemoryConfig" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._activeLocation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._activeLocation.ToString()) : null, "activeLocation" ,container.Add ); + } + AddIf( null != (((object)this._targetHciClusterId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetHciClusterId.ToString()) : null, "targetHciClusterId" ,container.Add ); + AddIf( null != (((object)this._targetArcClusterCustomLocationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetArcClusterCustomLocationId.ToString()) : null, "targetArcClusterCustomLocationId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetAzStackHciClusterName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetAzStackHciClusterName.ToString()) : null, "targetAzStackHciClusterName" ,container.Add ); + } + AddIf( null != (((object)this._storageContainerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageContainerId.ToString()) : null, "storageContainerId" ,container.Add ); + AddIf( null != (((object)this._targetResourceGroupId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetResourceGroupId.ToString()) : null, "targetResourceGroupId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetLocation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetLocation.ToString()) : null, "targetLocation" ,container.Add ); + } + AddIf( null != (((object)this._customLocationRegion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._customLocationRegion.ToString()) : null, "customLocationRegion" ,container.Add ); + if (null != this._disksToInclude) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._disksToInclude ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("disksToInclude",__w); + } + if (null != this._nicsToInclude) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __s in this._nicsToInclude ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("nicsToInclude",__r); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._protectedDisk) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __n in this._protectedDisk ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("protectedDisks",__m); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._protectedNic) + { + var __h = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __i in this._protectedNic ) + { + AddIf(__i?.ToJson(null, serializationMode) ,__h.Add); + } + container.Add("protectedNics",__h); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetVMBiosId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetVMBiosId.ToString()) : null, "targetVmBiosId" ,container.Add ); + } + AddIf( null != (((object)this._targetVMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetVMName.ToString()) : null, "targetVmName" ,container.Add ); + AddIf( null != (((object)this._hyperVGeneration)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._hyperVGeneration.ToString()) : null, "hyperVGeneration" ,container.Add ); + AddIf( null != (((object)this._targetNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetNetworkId.ToString()) : null, "targetNetworkId" ,container.Add ); + AddIf( null != (((object)this._testNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testNetworkId.ToString()) : null, "testNetworkId" ,container.Add ); + AddIf( null != this._targetCpuCore ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetCpuCore) : null, "targetCpuCores" ,container.Add ); + AddIf( null != this._isDynamicRam ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamicRam) : null, "isDynamicRam" ,container.Add ); + AddIf( null != this._targetMemoryInMegaByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetMemoryInMegaByte) : null, "targetMemoryInMegaBytes" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._oSType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._oSType.ToString()) : null, "osType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._oSName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._oSName.ToString()) : null, "osName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._firmwareType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._firmwareType.ToString()) : null, "firmwareType" ,container.Add ); + } + AddIf( null != (((object)this._fabricDiscoveryMachineId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._fabricDiscoveryMachineId.ToString()) : null, "fabricDiscoveryMachineId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceVMName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceVMName.ToString()) : null, "sourceVmName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._sourceCpuCore ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._sourceCpuCore) : null, "sourceCpuCores" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._sourceMemoryInMegaByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((double)this._sourceMemoryInMegaByte) : null, "sourceMemoryInMegaBytes" ,container.Add ); + } + AddIf( null != (((object)this._runAsAccountId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._runAsAccountId.ToString()) : null, "runAsAccountId" ,container.Add ); + AddIf( null != (((object)this._sourceFabricAgentName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceFabricAgentName.ToString()) : null, "sourceFabricAgentName" ,container.Add ); + AddIf( null != (((object)this._targetFabricAgentName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetFabricAgentName.ToString()) : null, "targetFabricAgentName" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceApplianceName.ToString()) : null, "sourceApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetApplianceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetApplianceName.ToString()) : null, "targetApplianceName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._failoverRecoveryPointId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._failoverRecoveryPointId.ToString()) : null, "failoverRecoveryPointId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastRecoveryPointReceived ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastRecoveryPointReceived?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastRecoveryPointReceived" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._lastRecoveryPointId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastRecoveryPointId.ToString()) : null, "lastRecoveryPointId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._initialReplicationProgressPercentage ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._initialReplicationProgressPercentage) : null, "initialReplicationProgressPercentage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._migrationProgressPercentage ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._migrationProgressPercentage) : null, "migrationProgressPercentage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resumeProgressPercentage ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._resumeProgressPercentage) : null, "resumeProgressPercentage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resyncProgressPercentage ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._resyncProgressPercentage) : null, "resyncProgressPercentage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resyncRetryCount ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._resyncRetryCount) : null, "resyncRetryCount" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resyncRequired ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._resyncRequired) : null, "resyncRequired" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resyncState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resyncState.ToString()) : null, "resyncState" ,container.Add ); + } + AddIf( null != this._performAutoResync ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._performAutoResync) : null, "performAutoResync" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._resumeRetryCount ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((long)this._resumeRetryCount) : null, "resumeRetryCount" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastReplicationUpdateTime ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._lastReplicationUpdateTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastReplicationUpdateTime" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHciprotectedItemModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __protectedItemModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomProperties(json); + {_dynamicMemoryConfig = If( json?.PropertyT("dynamicMemoryConfig"), out var __jsonDynamicMemoryConfig) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig.FromJson(__jsonDynamicMemoryConfig) : _dynamicMemoryConfig;} + {_activeLocation = If( json?.PropertyT("activeLocation"), out var __jsonActiveLocation) ? (string)__jsonActiveLocation : (string)_activeLocation;} + {_targetHciClusterId = If( json?.PropertyT("targetHciClusterId"), out var __jsonTargetHciClusterId) ? (string)__jsonTargetHciClusterId : (string)_targetHciClusterId;} + {_targetArcClusterCustomLocationId = If( json?.PropertyT("targetArcClusterCustomLocationId"), out var __jsonTargetArcClusterCustomLocationId) ? (string)__jsonTargetArcClusterCustomLocationId : (string)_targetArcClusterCustomLocationId;} + {_targetAzStackHciClusterName = If( json?.PropertyT("targetAzStackHciClusterName"), out var __jsonTargetAzStackHciClusterName) ? (string)__jsonTargetAzStackHciClusterName : (string)_targetAzStackHciClusterName;} + {_storageContainerId = If( json?.PropertyT("storageContainerId"), out var __jsonStorageContainerId) ? (string)__jsonStorageContainerId : (string)_storageContainerId;} + {_targetResourceGroupId = If( json?.PropertyT("targetResourceGroupId"), out var __jsonTargetResourceGroupId) ? (string)__jsonTargetResourceGroupId : (string)_targetResourceGroupId;} + {_targetLocation = If( json?.PropertyT("targetLocation"), out var __jsonTargetLocation) ? (string)__jsonTargetLocation : (string)_targetLocation;} + {_customLocationRegion = If( json?.PropertyT("customLocationRegion"), out var __jsonCustomLocationRegion) ? (string)__jsonCustomLocationRegion : (string)_customLocationRegion;} + {_disksToInclude = If( json?.PropertyT("disksToInclude"), out var __jsonDisksToInclude) ? If( __jsonDisksToInclude as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcidiskInput) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcidiskInput.FromJson(__u) )) ))() : null : _disksToInclude;} + {_nicsToInclude = If( json?.PropertyT("nicsToInclude"), out var __jsonNicsToInclude) ? If( __jsonNicsToInclude as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcinicInput.FromJson(__p) )) ))() : null : _nicsToInclude;} + {_protectedDisk = If( json?.PropertyT("protectedDisks"), out var __jsonProtectedDisks) ? If( __jsonProtectedDisks as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedDiskProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHciprotectedDiskProperties.FromJson(__k) )) ))() : null : _protectedDisk;} + {_protectedNic = If( json?.PropertyT("protectedNics"), out var __jsonProtectedNics) ? If( __jsonProtectedNics as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonArray, out var __g) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__g, (__f)=>(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHciprotectedNicProperties.FromJson(__f) )) ))() : null : _protectedNic;} + {_targetVMBiosId = If( json?.PropertyT("targetVmBiosId"), out var __jsonTargetVMBiosId) ? (string)__jsonTargetVMBiosId : (string)_targetVMBiosId;} + {_targetVMName = If( json?.PropertyT("targetVmName"), out var __jsonTargetVMName) ? (string)__jsonTargetVMName : (string)_targetVMName;} + {_hyperVGeneration = If( json?.PropertyT("hyperVGeneration"), out var __jsonHyperVGeneration) ? (string)__jsonHyperVGeneration : (string)_hyperVGeneration;} + {_targetNetworkId = If( json?.PropertyT("targetNetworkId"), out var __jsonTargetNetworkId) ? (string)__jsonTargetNetworkId : (string)_targetNetworkId;} + {_testNetworkId = If( json?.PropertyT("testNetworkId"), out var __jsonTestNetworkId) ? (string)__jsonTestNetworkId : (string)_testNetworkId;} + {_targetCpuCore = If( json?.PropertyT("targetCpuCores"), out var __jsonTargetCpuCores) ? (int?)__jsonTargetCpuCores : _targetCpuCore;} + {_isDynamicRam = If( json?.PropertyT("isDynamicRam"), out var __jsonIsDynamicRam) ? (bool?)__jsonIsDynamicRam : _isDynamicRam;} + {_targetMemoryInMegaByte = If( json?.PropertyT("targetMemoryInMegaBytes"), out var __jsonTargetMemoryInMegaBytes) ? (int?)__jsonTargetMemoryInMegaBytes : _targetMemoryInMegaByte;} + {_oSType = If( json?.PropertyT("osType"), out var __jsonOSType) ? (string)__jsonOSType : (string)_oSType;} + {_oSName = If( json?.PropertyT("osName"), out var __jsonOSName) ? (string)__jsonOSName : (string)_oSName;} + {_firmwareType = If( json?.PropertyT("firmwareType"), out var __jsonFirmwareType) ? (string)__jsonFirmwareType : (string)_firmwareType;} + {_fabricDiscoveryMachineId = If( json?.PropertyT("fabricDiscoveryMachineId"), out var __jsonFabricDiscoveryMachineId) ? (string)__jsonFabricDiscoveryMachineId : (string)_fabricDiscoveryMachineId;} + {_sourceVMName = If( json?.PropertyT("sourceVmName"), out var __jsonSourceVMName) ? (string)__jsonSourceVMName : (string)_sourceVMName;} + {_sourceCpuCore = If( json?.PropertyT("sourceCpuCores"), out var __jsonSourceCpuCores) ? (int?)__jsonSourceCpuCores : _sourceCpuCore;} + {_sourceMemoryInMegaByte = If( json?.PropertyT("sourceMemoryInMegaBytes"), out var __jsonSourceMemoryInMegaBytes) ? (double?)__jsonSourceMemoryInMegaBytes : _sourceMemoryInMegaByte;} + {_runAsAccountId = If( json?.PropertyT("runAsAccountId"), out var __jsonRunAsAccountId) ? (string)__jsonRunAsAccountId : (string)_runAsAccountId;} + {_sourceFabricAgentName = If( json?.PropertyT("sourceFabricAgentName"), out var __jsonSourceFabricAgentName) ? (string)__jsonSourceFabricAgentName : (string)_sourceFabricAgentName;} + {_targetFabricAgentName = If( json?.PropertyT("targetFabricAgentName"), out var __jsonTargetFabricAgentName) ? (string)__jsonTargetFabricAgentName : (string)_targetFabricAgentName;} + {_sourceApplianceName = If( json?.PropertyT("sourceApplianceName"), out var __jsonSourceApplianceName) ? (string)__jsonSourceApplianceName : (string)_sourceApplianceName;} + {_targetApplianceName = If( json?.PropertyT("targetApplianceName"), out var __jsonTargetApplianceName) ? (string)__jsonTargetApplianceName : (string)_targetApplianceName;} + {_failoverRecoveryPointId = If( json?.PropertyT("failoverRecoveryPointId"), out var __jsonFailoverRecoveryPointId) ? (string)__jsonFailoverRecoveryPointId : (string)_failoverRecoveryPointId;} + {_lastRecoveryPointReceived = If( json?.PropertyT("lastRecoveryPointReceived"), out var __jsonLastRecoveryPointReceived) ? global::System.DateTime.TryParse((string)__jsonLastRecoveryPointReceived, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastRecoveryPointReceivedValue) ? __jsonLastRecoveryPointReceivedValue : _lastRecoveryPointReceived : _lastRecoveryPointReceived;} + {_lastRecoveryPointId = If( json?.PropertyT("lastRecoveryPointId"), out var __jsonLastRecoveryPointId) ? (string)__jsonLastRecoveryPointId : (string)_lastRecoveryPointId;} + {_initialReplicationProgressPercentage = If( json?.PropertyT("initialReplicationProgressPercentage"), out var __jsonInitialReplicationProgressPercentage) ? (int?)__jsonInitialReplicationProgressPercentage : _initialReplicationProgressPercentage;} + {_migrationProgressPercentage = If( json?.PropertyT("migrationProgressPercentage"), out var __jsonMigrationProgressPercentage) ? (int?)__jsonMigrationProgressPercentage : _migrationProgressPercentage;} + {_resumeProgressPercentage = If( json?.PropertyT("resumeProgressPercentage"), out var __jsonResumeProgressPercentage) ? (int?)__jsonResumeProgressPercentage : _resumeProgressPercentage;} + {_resyncProgressPercentage = If( json?.PropertyT("resyncProgressPercentage"), out var __jsonResyncProgressPercentage) ? (int?)__jsonResyncProgressPercentage : _resyncProgressPercentage;} + {_resyncRetryCount = If( json?.PropertyT("resyncRetryCount"), out var __jsonResyncRetryCount) ? (long?)__jsonResyncRetryCount : _resyncRetryCount;} + {_resyncRequired = If( json?.PropertyT("resyncRequired"), out var __jsonResyncRequired) ? (bool?)__jsonResyncRequired : _resyncRequired;} + {_resyncState = If( json?.PropertyT("resyncState"), out var __jsonResyncState) ? (string)__jsonResyncState : (string)_resyncState;} + {_performAutoResync = If( json?.PropertyT("performAutoResync"), out var __jsonPerformAutoResync) ? (bool?)__jsonPerformAutoResync : _performAutoResync;} + {_resumeRetryCount = If( json?.PropertyT("resumeRetryCount"), out var __jsonResumeRetryCount) ? (long?)__jsonResumeRetryCount : _resumeRetryCount;} + {_lastReplicationUpdateTime = If( json?.PropertyT("lastReplicationUpdateTime"), out var __jsonLastReplicationUpdateTime) ? global::System.DateTime.TryParse((string)__jsonLastReplicationUpdateTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastReplicationUpdateTimeValue) ? __jsonLastReplicationUpdateTimeValue : _lastReplicationUpdateTime : _lastReplicationUpdateTime;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.PowerShell.cs new file mode 100644 index 00000000000..087a85d3d8d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.PowerShell.cs @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateTypeConverter))] + public partial class VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the + /// content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__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 VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DynamicMemoryConfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig) content.GetValueForProperty("DynamicMemoryConfig",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfig, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfigTypeConverter.ConvertFrom); + } + if (content.Contains("NicsToInclude")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude = (System.Collections.Generic.List) content.GetValueForProperty("NicsToInclude",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).NicsToInclude, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcinicInputTypeConverter.ConvertFrom)); + } + if (content.Contains("TargetCpuCore")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore = (int?) content.GetValueForProperty("TargetCpuCore",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetCpuCore, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("IsDynamicRam")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam = (bool?) content.GetValueForProperty("IsDynamicRam",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).IsDynamicRam, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte = (int?) content.GetValueForProperty("TargetMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).TargetMemoryInMegaByte, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("OSType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType = (string) content.GetValueForProperty("OSType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).OSType, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)this).InstanceType, global::System.Convert.ToString); + } + if (content.Contains("DynamicMemoryConfigMaximumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMaximumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMaximumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigMinimumMemoryInMegaByte")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte = (long?) content.GetValueForProperty("DynamicMemoryConfigMinimumMemoryInMegaByte",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigMinimumMemoryInMegaByte, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("DynamicMemoryConfigTargetMemoryBufferPercentage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage = (int?) content.GetValueForProperty("DynamicMemoryConfigTargetMemoryBufferPercentage",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal)this).DynamicMemoryConfigTargetMemoryBufferPercentage, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializePSObject(content); + } + } + /// VMware to AzStackHCI Protected item model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateTypeConverter))] + public partial interface IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.TypeConverter.cs new file mode 100644 index 00000000000..3574f9b5699 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.cs new file mode 100644 index 00000000000..7d969ca8a8a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI Protected item model custom properties. + public partial class VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate __protectedItemModelCustomPropertiesUpdate = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate(); + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig _dynamicMemoryConfig; + + /// Protected item dynamic memory config. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set => this._dynamicMemoryConfig = value; } + + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMaximumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MaximumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public long? DynamicMemoryConfigMinimumMemoryInMegaByte { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).MinimumMemoryInMegaByte = value ?? default(long); } + + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public int? DynamicMemoryConfigTargetMemoryBufferPercentage { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfigInternal)DynamicMemoryConfig).TargetMemoryBufferPercentage = value ?? default(int); } + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal)__protectedItemModelCustomPropertiesUpdate).InstanceType = "VMwareToAzStackHCI"; } + + /// Backing field for property. + private bool? _isDynamicRam; + + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsDynamicRam { get => this._isDynamicRam; set => this._isDynamicRam = value; } + + /// Internal Acessors for DynamicMemoryConfig + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal.DynamicMemoryConfig { get => (this._dynamicMemoryConfig = this._dynamicMemoryConfig ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig()); set { {_dynamicMemoryConfig = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _nicsToInclude; + + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List NicsToInclude { get => this._nicsToInclude; set => this._nicsToInclude = value; } + + /// Backing field for property. + private string _oSType; + + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string OSType { get => this._oSType; set => this._oSType = value; } + + /// Backing field for property. + private int? _targetCpuCore; + + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetCpuCore { get => this._targetCpuCore; set => this._targetCpuCore = value; } + + /// Backing field for property. + private int? _targetMemoryInMegaByte; + + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public int? TargetMemoryInMegaByte { get => this._targetMemoryInMegaByte; set => this._targetMemoryInMegaByte = value; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate() + { + this.__protectedItemModelCustomPropertiesUpdate.InstanceType = "VMwareToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__protectedItemModelCustomPropertiesUpdate), __protectedItemModelCustomPropertiesUpdate); + await eventListener.AssertObjectIsValid(nameof(__protectedItemModelCustomPropertiesUpdate), __protectedItemModelCustomPropertiesUpdate); + } + } + /// VMware to AzStackHCI Protected item model custom properties. + public partial interface IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdate + { + /// Gets or sets maximum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets maximum memory in MB.", + SerializedName = @"maximumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets minimum memory in MB.", + SerializedName = @"minimumMemoryInMegaBytes", + PossibleTypes = new [] { typeof(long) })] + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets target memory buffer in %.", + SerializedName = @"targetMemoryBufferPercentage", + PossibleTypes = new [] { typeof(int) })] + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets a value indicating whether memory is dynamical. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether memory is dynamical.", + SerializedName = @"isDynamicRam", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDynamicRam { get; set; } + /// Gets or sets the list of VM NIC to replicate. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the list of VM NIC to replicate.", + SerializedName = @"nicsToInclude", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput) })] + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the type of the OS. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of the OS.", + SerializedName = @"osType", + PossibleTypes = new [] { typeof(string) })] + string OSType { get; set; } + /// Gets or sets the target CPU cores. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target CPU cores.", + SerializedName = @"targetCpuCores", + PossibleTypes = new [] { typeof(int) })] + int? TargetCpuCore { get; set; } + /// Gets or sets the target memory in mega-bytes. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the target memory in mega-bytes.", + SerializedName = @"targetMemoryInMegaBytes", + PossibleTypes = new [] { typeof(int) })] + int? TargetMemoryInMegaByte { get; set; } + + } + /// VMware to AzStackHCI Protected item model custom properties. + internal partial interface IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdateInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelCustomPropertiesUpdateInternal + { + /// Protected item dynamic memory config. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemDynamicMemoryConfig DynamicMemoryConfig { get; set; } + /// Gets or sets maximum memory in MB. + long? DynamicMemoryConfigMaximumMemoryInMegaByte { get; set; } + /// Gets or sets minimum memory in MB. + long? DynamicMemoryConfigMinimumMemoryInMegaByte { get; set; } + /// Gets or sets target memory buffer in %. + int? DynamicMemoryConfigTargetMemoryBufferPercentage { get; set; } + /// Gets or sets a value indicating whether memory is dynamical. + bool? IsDynamicRam { get; set; } + /// Gets or sets the list of VM NIC to replicate. + System.Collections.Generic.List NicsToInclude { get; set; } + /// Gets or sets the type of the OS. + string OSType { get; set; } + /// Gets or sets the target CPU cores. + int? TargetCpuCore { get; set; } + /// Gets or sets the target memory in mega-bytes. + int? TargetMemoryInMegaByte { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.json.cs new file mode 100644 index 00000000000..4b502b6321d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate.json.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI Protected item model custom properties. + public partial class VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __protectedItemModelCustomPropertiesUpdate?.ToJson(container, serializationMode); + AddIf( null != this._dynamicMemoryConfig ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._dynamicMemoryConfig.ToJson(null,serializationMode) : null, "dynamicMemoryConfig" ,container.Add ); + if (null != this._nicsToInclude) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._nicsToInclude ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("nicsToInclude",__w); + } + AddIf( null != this._targetCpuCore ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetCpuCore) : null, "targetCpuCores" ,container.Add ); + AddIf( null != this._isDynamicRam ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isDynamicRam) : null, "isDynamicRam" ,container.Add ); + AddIf( null != this._targetMemoryInMegaByte ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNumber((int)this._targetMemoryInMegaByte) : null, "targetMemoryInMegaBytes" ,container.Add ); + AddIf( null != (((object)this._oSType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._oSType.ToString()) : null, "osType" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHciprotectedItemModelCustomPropertiesUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __protectedItemModelCustomPropertiesUpdate = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelCustomPropertiesUpdate(json); + {_dynamicMemoryConfig = If( json?.PropertyT("dynamicMemoryConfig"), out var __jsonDynamicMemoryConfig) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemDynamicMemoryConfig.FromJson(__jsonDynamicMemoryConfig) : _dynamicMemoryConfig;} + {_nicsToInclude = If( json?.PropertyT("nicsToInclude"), out var __jsonNicsToInclude) ? If( __jsonNicsToInclude as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcinicInput) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VMwareToAzStackHcinicInput.FromJson(__u) )) ))() : null : _nicsToInclude;} + {_targetCpuCore = If( json?.PropertyT("targetCpuCores"), out var __jsonTargetCpuCores) ? (int?)__jsonTargetCpuCores : _targetCpuCore;} + {_isDynamicRam = If( json?.PropertyT("isDynamicRam"), out var __jsonIsDynamicRam) ? (bool?)__jsonIsDynamicRam : _isDynamicRam;} + {_targetMemoryInMegaByte = If( json?.PropertyT("targetMemoryInMegaBytes"), out var __jsonTargetMemoryInMegaBytes) ? (int?)__jsonTargetMemoryInMegaBytes : _targetMemoryInMegaByte;} + {_oSType = If( json?.PropertyT("osType"), out var __jsonOSType) ? (string)__jsonOSType : (string)_oSType;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.PowerShell.cs new file mode 100644 index 00000000000..949b87a2f20 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMwareToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedNicPropertiesTypeConverter))] + public partial class VMwareToAzStackHciprotectedNicProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHciprotectedNicProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHciprotectedNicProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHciprotectedNicProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("MacAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).MacAddress = (string) content.GetValueForProperty("MacAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).MacAddress, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).Label, global::System.Convert.ToString); + } + if (content.Contains("IsPrimaryNic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).IsPrimaryNic = (bool?) content.GetValueForProperty("IsPrimaryNic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).IsPrimaryNic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover, 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 VMwareToAzStackHciprotectedNicProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NicId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NicId = (string) content.GetValueForProperty("NicId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NicId, global::System.Convert.ToString); + } + if (content.Contains("MacAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).MacAddress = (string) content.GetValueForProperty("MacAddress",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).MacAddress, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).Label, global::System.Convert.ToString); + } + if (content.Contains("IsPrimaryNic")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).IsPrimaryNic = (bool?) content.GetValueForProperty("IsPrimaryNic",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).IsPrimaryNic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("NetworkName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NetworkName = (string) content.GetValueForProperty("NetworkName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).NetworkName, global::System.Convert.ToString); + } + if (content.Contains("TargetNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId = (string) content.GetValueForProperty("TargetNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TargetNetworkId, global::System.Convert.ToString); + } + if (content.Contains("TestNetworkId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId = (string) content.GetValueForProperty("TestNetworkId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).TestNetworkId, global::System.Convert.ToString); + } + if (content.Contains("SelectionTypeForFailover")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover = (string) content.GetValueForProperty("SelectionTypeForFailover",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal)this).SelectionTypeForFailover, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMwareToAzStackHCI NIC properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHciprotectedNicPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHciprotectedNicProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.TypeConverter.cs new file mode 100644 index 00000000000..fe02855a485 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHciprotectedNicPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHciprotectedNicProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedNicProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHciprotectedNicProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.cs new file mode 100644 index 00000000000..a2f922e69a6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStackHCI NIC properties. + public partial class VMwareToAzStackHciprotectedNicProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal + { + + /// Backing field for property. + private bool? _isPrimaryNic; + + /// Gets or sets a value indicating whether this is the primary NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public bool? IsPrimaryNic { get => this._isPrimaryNic; set => this._isPrimaryNic = value; } + + /// Backing field for property. + private string _label; + + /// Gets or sets the NIC label. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Label { get => this._label; } + + /// Backing field for property. + private string _macAddress; + + /// Gets or sets the NIC mac address. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string MacAddress { get => this._macAddress; } + + /// Internal Acessors for Label + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.Label { get => this._label; set { {_label = value;} } } + + /// Internal Acessors for MacAddress + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.MacAddress { get => this._macAddress; set { {_macAddress = value;} } } + + /// Internal Acessors for NetworkName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.NetworkName { get => this._networkName; set { {_networkName = value;} } } + + /// Internal Acessors for NicId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.NicId { get => this._nicId; set { {_nicId = value;} } } + + /// Internal Acessors for SelectionTypeForFailover + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.SelectionTypeForFailover { get => this._selectionTypeForFailover; set { {_selectionTypeForFailover = value;} } } + + /// Internal Acessors for TargetNetworkId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.TargetNetworkId { get => this._targetNetworkId; set { {_targetNetworkId = value;} } } + + /// Internal Acessors for TestNetworkId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicPropertiesInternal.TestNetworkId { get => this._testNetworkId; set { {_testNetworkId = value;} } } + + /// Backing field for property. + private string _networkName; + + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NetworkName { get => this._networkName; } + + /// Backing field for property. + private string _nicId; + + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NicId { get => this._nicId; } + + /// Backing field for property. + private string _selectionTypeForFailover; + + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SelectionTypeForFailover { get => this._selectionTypeForFailover; } + + /// Backing field for property. + private string _targetNetworkId; + + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetNetworkId { get => this._targetNetworkId; } + + /// Backing field for property. + private string _testNetworkId; + + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TestNetworkId { get => this._testNetworkId; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHciprotectedNicProperties() + { + + } + } + /// VMwareToAzStackHCI NIC properties. + public partial interface IVMwareToAzStackHciprotectedNicProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets a value indicating whether this is the primary NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets a value indicating whether this is the primary NIC.", + SerializedName = @"isPrimaryNic", + PossibleTypes = new [] { typeof(bool) })] + bool? IsPrimaryNic { get; set; } + /// Gets or sets the NIC label. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the NIC label.", + SerializedName = @"label", + PossibleTypes = new [] { typeof(string) })] + string Label { get; } + /// Gets or sets the NIC mac address. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the NIC mac address.", + SerializedName = @"macAddress", + PossibleTypes = new [] { typeof(string) })] + string MacAddress { get; } + /// Gets or sets the network name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the network name.", + SerializedName = @"networkName", + PossibleTypes = new [] { typeof(string) })] + string NetworkName { get; } + /// Gets or sets the NIC Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the NIC Id.", + SerializedName = @"nicId", + PossibleTypes = new [] { typeof(string) })] + string NicId { get; } + /// Gets or sets the selection type of the NIC. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the selection type of the NIC.", + SerializedName = @"selectionTypeForFailover", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target network Id within AzStackHCI Cluster.", + SerializedName = @"targetNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TargetNetworkId { get; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target test network Id within AzStackHCI Cluster.", + SerializedName = @"testNetworkId", + PossibleTypes = new [] { typeof(string) })] + string TestNetworkId { get; } + + } + /// VMwareToAzStackHCI NIC properties. + internal partial interface IVMwareToAzStackHciprotectedNicPropertiesInternal + + { + /// Gets or sets a value indicating whether this is the primary NIC. + bool? IsPrimaryNic { get; set; } + /// Gets or sets the NIC label. + string Label { get; set; } + /// Gets or sets the NIC mac address. + string MacAddress { get; set; } + /// Gets or sets the network name. + string NetworkName { get; set; } + /// Gets or sets the NIC Id. + string NicId { get; set; } + /// Gets or sets the selection type of the NIC. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("NotSelected", "SelectedByUser", "SelectedByDefault", "SelectedByUserOverride")] + string SelectionTypeForFailover { get; set; } + /// Gets or sets the target network Id within AzStackHCI Cluster. + string TargetNetworkId { get; set; } + /// Gets or sets the target test network Id within AzStackHCI Cluster. + string TestNetworkId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.json.cs new file mode 100644 index 00000000000..419589a2471 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHciprotectedNicProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMwareToAzStackHCI NIC properties. + public partial class VMwareToAzStackHciprotectedNicProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHciprotectedNicProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHciprotectedNicProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._nicId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._nicId.ToString()) : null, "nicId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._macAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._macAddress.ToString()) : null, "macAddress" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._label)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._label.ToString()) : null, "label" ,container.Add ); + } + AddIf( null != this._isPrimaryNic ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonBoolean((bool)this._isPrimaryNic) : null, "isPrimaryNic" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._networkName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._networkName.ToString()) : null, "networkName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetNetworkId.ToString()) : null, "targetNetworkId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._testNetworkId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._testNetworkId.ToString()) : null, "testNetworkId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._selectionTypeForFailover)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._selectionTypeForFailover.ToString()) : null, "selectionTypeForFailover" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHciprotectedNicProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nicId = If( json?.PropertyT("nicId"), out var __jsonNicId) ? (string)__jsonNicId : (string)_nicId;} + {_macAddress = If( json?.PropertyT("macAddress"), out var __jsonMacAddress) ? (string)__jsonMacAddress : (string)_macAddress;} + {_label = If( json?.PropertyT("label"), out var __jsonLabel) ? (string)__jsonLabel : (string)_label;} + {_isPrimaryNic = If( json?.PropertyT("isPrimaryNic"), out var __jsonIsPrimaryNic) ? (bool?)__jsonIsPrimaryNic : _isPrimaryNic;} + {_networkName = If( json?.PropertyT("networkName"), out var __jsonNetworkName) ? (string)__jsonNetworkName : (string)_networkName;} + {_targetNetworkId = If( json?.PropertyT("targetNetworkId"), out var __jsonTargetNetworkId) ? (string)__jsonTargetNetworkId : (string)_targetNetworkId;} + {_testNetworkId = If( json?.PropertyT("testNetworkId"), out var __jsonTestNetworkId) ? (string)__jsonTestNetworkId : (string)_testNetworkId;} + {_selectionTypeForFailover = If( json?.PropertyT("selectionTypeForFailover"), out var __jsonSelectionTypeForFailover) ? (string)__jsonSelectionTypeForFailover : (string)_selectionTypeForFailover;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..6b70f47de2a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.PowerShell.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware to AzStackHCI recovery point model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcirecoveryPointModelCustomPropertiesTypeConverter))] + public partial class VMwareToAzStackHcirecoveryPointModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHcirecoveryPointModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHcirecoveryPointModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content + /// from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHcirecoveryPointModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId = (System.Collections.Generic.List) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType, 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 VMwareToAzStackHcirecoveryPointModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DiskId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId = (System.Collections.Generic.List) content.GetValueForProperty("DiskId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal)this).DiskId, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware to AzStackHCI recovery point model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcirecoveryPointModelCustomPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHcirecoveryPointModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..34b74897b3e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHcirecoveryPointModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHcirecoveryPointModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHcirecoveryPointModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHcirecoveryPointModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.cs new file mode 100644 index 00000000000..cc4b5f32817 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI recovery point model custom properties. + public partial class VMwareToAzStackHcirecoveryPointModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties __recoveryPointModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties(); + + /// Backing field for property. + private System.Collections.Generic.List _diskId; + + /// Gets or sets the list of the disk Ids. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List DiskId { get => this._diskId; } + + /// Discriminator property for RecoveryPointModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCIRecoveryPointModelCustomProperties"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal)__recoveryPointModelCustomProperties).InstanceType = "VMwareToAzStackHCIRecoveryPointModelCustomProperties"; } + + /// Internal Acessors for DiskId + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal.DiskId { get => this._diskId; set { {_diskId = value;} } } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHcirecoveryPointModelCustomProperties() + { + this.__recoveryPointModelCustomProperties.InstanceType = "VMwareToAzStackHCIRecoveryPointModelCustomProperties"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__recoveryPointModelCustomProperties), __recoveryPointModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__recoveryPointModelCustomProperties), __recoveryPointModelCustomProperties); + } + } + /// VMware to AzStackHCI recovery point model custom properties. + public partial interface IVMwareToAzStackHcirecoveryPointModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomProperties + { + /// Gets or sets the list of the disk Ids. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the list of the disk Ids.", + SerializedName = @"diskIds", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List DiskId { get; } + + } + /// VMware to AzStackHCI recovery point model custom properties. + internal partial interface IVMwareToAzStackHcirecoveryPointModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModelCustomPropertiesInternal + { + /// Gets or sets the list of the disk Ids. + System.Collections.Generic.List DiskId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.json.cs new file mode 100644 index 00000000000..9c89ad144e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcirecoveryPointModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI recovery point model custom properties. + public partial class VMwareToAzStackHcirecoveryPointModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcirecoveryPointModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHcirecoveryPointModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __recoveryPointModelCustomProperties?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._diskId) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.XNodeArray(); + foreach( var __x in this._diskId ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("diskIds",__w); + } + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHcirecoveryPointModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __recoveryPointModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.RecoveryPointModelCustomProperties(json); + {_diskId = If( json?.PropertyT("diskIds"), out var __jsonDiskIds) ? If( __jsonDiskIds as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _diskId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.PowerShell.cs new file mode 100644 index 00000000000..9ae861593f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.PowerShell.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// VMware to AzStackHCI Replication extension model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcireplicationExtensionModelCustomPropertiesTypeConverter))] + public partial class VMwareToAzStackHcireplicationExtensionModelCustomProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VMwareToAzStackHcireplicationExtensionModelCustomProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VMwareToAzStackHcireplicationExtensionModelCustomProperties(content); + } + + /// + /// Creates a new instance of , deserializing the + /// content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VMwareToAzStackHcireplicationExtensionModelCustomProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("VmwareFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareFabricArmId = (string) content.GetValueForProperty("VmwareFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("VmwareSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareSiteId = (string) content.GetValueForProperty("VmwareSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareSiteId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId = (string) content.GetValueForProperty("AzStackHciFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId = (string) content.GetValueForProperty("AzStackHciSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId = (string) content.GetValueForProperty("StorageAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountSasSecretName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName = (string) content.GetValueForProperty("StorageAccountSasSecretName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName, global::System.Convert.ToString); + } + if (content.Contains("AsrServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri = (string) content.GetValueForProperty("AsrServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri, global::System.Convert.ToString); + } + if (content.Contains("RcmServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri = (string) content.GetValueForProperty("RcmServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri, global::System.Convert.ToString); + } + if (content.Contains("GatewayServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri = (string) content.GetValueForProperty("GatewayServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri, global::System.Convert.ToString); + } + if (content.Contains("SourceGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId = (string) content.GetValueForProperty("SourceGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("TargetGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId = (string) content.GetValueForProperty("TargetGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("SourceStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName = (string) content.GetValueForProperty("SourceStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("TargetStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName = (string) content.GetValueForProperty("TargetStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("ResourceLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation = (string) content.GetValueForProperty("ResourceLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup = (string) content.GetValueForProperty("ResourceGroup",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType, 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 VMwareToAzStackHcireplicationExtensionModelCustomProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("VmwareFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareFabricArmId = (string) content.GetValueForProperty("VmwareFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("VmwareSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareSiteId = (string) content.GetValueForProperty("VmwareSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).VmwareSiteId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciFabricArmId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId = (string) content.GetValueForProperty("AzStackHciFabricArmId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciFabricArmId, global::System.Convert.ToString); + } + if (content.Contains("AzStackHciSiteId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId = (string) content.GetValueForProperty("AzStackHciSiteId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AzStackHciSiteId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId = (string) content.GetValueForProperty("StorageAccountId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountId, global::System.Convert.ToString); + } + if (content.Contains("StorageAccountSasSecretName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName = (string) content.GetValueForProperty("StorageAccountSasSecretName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).StorageAccountSasSecretName, global::System.Convert.ToString); + } + if (content.Contains("AsrServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri = (string) content.GetValueForProperty("AsrServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).AsrServiceUri, global::System.Convert.ToString); + } + if (content.Contains("RcmServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri = (string) content.GetValueForProperty("RcmServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).RcmServiceUri, global::System.Convert.ToString); + } + if (content.Contains("GatewayServiceUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri = (string) content.GetValueForProperty("GatewayServiceUri",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).GatewayServiceUri, global::System.Convert.ToString); + } + if (content.Contains("SourceGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId = (string) content.GetValueForProperty("SourceGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("TargetGatewayServiceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId = (string) content.GetValueForProperty("TargetGatewayServiceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetGatewayServiceId, global::System.Convert.ToString); + } + if (content.Contains("SourceStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName = (string) content.GetValueForProperty("SourceStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SourceStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("TargetStorageContainerName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName = (string) content.GetValueForProperty("TargetStorageContainerName",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).TargetStorageContainerName, global::System.Convert.ToString); + } + if (content.Contains("ResourceLocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation = (string) content.GetValueForProperty("ResourceLocation",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceLocation, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup = (string) content.GetValueForProperty("ResourceGroup",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal)this).ResourceGroup, global::System.Convert.ToString); + } + if (content.Contains("InstanceType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)this).InstanceType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// VMware to AzStackHCI Replication extension model custom properties. + [System.ComponentModel.TypeConverter(typeof(VMwareToAzStackHcireplicationExtensionModelCustomPropertiesTypeConverter))] + public partial interface IVMwareToAzStackHcireplicationExtensionModelCustomProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.TypeConverter.cs new file mode 100644 index 00000000000..506b0de8f8c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VMwareToAzStackHcireplicationExtensionModelCustomPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is + /// 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.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VMwareToAzStackHcireplicationExtensionModelCustomProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VMwareToAzStackHcireplicationExtensionModelCustomProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VMwareToAzStackHcireplicationExtensionModelCustomProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.cs new file mode 100644 index 00000000000..0dbb5e5cd02 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.cs @@ -0,0 +1,414 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI Replication extension model custom properties. + public partial class VMwareToAzStackHcireplicationExtensionModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties __replicationExtensionModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties(); + + /// Backing field for property. + private string _asrServiceUri; + + /// Gets or sets the Uri of ASR. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AsrServiceUri { get => this._asrServiceUri; } + + /// Backing field for property. + private string _azStackHciFabricArmId; + + /// Gets or sets the ARM Id of the target AzStackHCI fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AzStackHciFabricArmId { get => this._azStackHciFabricArmId; set => this._azStackHciFabricArmId = value; } + + /// Backing field for property. + private string _azStackHciSiteId; + + /// Gets or sets the ARM Id of the AzStackHCI site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string AzStackHciSiteId { get => this._azStackHciSiteId; } + + /// Backing field for property. + private string _gatewayServiceUri; + + /// Gets or sets the Uri of Gateway. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string GatewayServiceUri { get => this._gatewayServiceUri; } + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Constant] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string InstanceType { get => "VMwareToAzStackHCI"; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal)__replicationExtensionModelCustomProperties).InstanceType = "VMwareToAzStackHCI"; } + + /// Internal Acessors for AsrServiceUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.AsrServiceUri { get => this._asrServiceUri; set { {_asrServiceUri = value;} } } + + /// Internal Acessors for AzStackHciSiteId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.AzStackHciSiteId { get => this._azStackHciSiteId; set { {_azStackHciSiteId = value;} } } + + /// Internal Acessors for GatewayServiceUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.GatewayServiceUri { get => this._gatewayServiceUri; set { {_gatewayServiceUri = value;} } } + + /// Internal Acessors for RcmServiceUri + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.RcmServiceUri { get => this._rcmServiceUri; set { {_rcmServiceUri = value;} } } + + /// Internal Acessors for ResourceGroup + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.ResourceGroup { get => this._resourceGroup; set { {_resourceGroup = value;} } } + + /// Internal Acessors for ResourceLocation + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.ResourceLocation { get => this._resourceLocation; set { {_resourceLocation = value;} } } + + /// Internal Acessors for SourceGatewayServiceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.SourceGatewayServiceId { get => this._sourceGatewayServiceId; set { {_sourceGatewayServiceId = value;} } } + + /// Internal Acessors for SourceStorageContainerName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.SourceStorageContainerName { get => this._sourceStorageContainerName; set { {_sourceStorageContainerName = value;} } } + + /// Internal Acessors for SubscriptionId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.SubscriptionId { get => this._subscriptionId; set { {_subscriptionId = value;} } } + + /// Internal Acessors for TargetGatewayServiceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.TargetGatewayServiceId { get => this._targetGatewayServiceId; set { {_targetGatewayServiceId = value;} } } + + /// Internal Acessors for TargetStorageContainerName + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.TargetStorageContainerName { get => this._targetStorageContainerName; set { {_targetStorageContainerName = value;} } } + + /// Internal Acessors for VmwareSiteId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal.VmwareSiteId { get => this._vmwareSiteId; set { {_vmwareSiteId = value;} } } + + /// Backing field for property. + private string _rcmServiceUri; + + /// Gets or sets the Uri of Rcm. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string RcmServiceUri { get => this._rcmServiceUri; } + + /// Backing field for property. + private string _resourceGroup; + + /// Gets or sets the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceGroup { get => this._resourceGroup; } + + /// Backing field for property. + private string _resourceLocation; + + /// Gets or sets the resource location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ResourceLocation { get => this._resourceLocation; } + + /// Backing field for property. + private string _sourceGatewayServiceId; + + /// Gets or sets the gateway service Id of source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceGatewayServiceId { get => this._sourceGatewayServiceId; } + + /// Backing field for property. + private string _sourceStorageContainerName; + + /// Gets or sets the source storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SourceStorageContainerName { get => this._sourceStorageContainerName; } + + /// Backing field for property. + private string _storageAccountId; + + /// Gets or sets the storage account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageAccountId { get => this._storageAccountId; set => this._storageAccountId = value; } + + /// Backing field for property. + private string _storageAccountSasSecretName; + + /// Gets or sets the Sas Secret of storage account. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string StorageAccountSasSecretName { get => this._storageAccountSasSecretName; set => this._storageAccountSasSecretName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// Gets or sets the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; } + + /// Backing field for property. + private string _targetGatewayServiceId; + + /// Gets or sets the gateway service Id of target. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetGatewayServiceId { get => this._targetGatewayServiceId; } + + /// Backing field for property. + private string _targetStorageContainerName; + + /// Gets or sets the target storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TargetStorageContainerName { get => this._targetStorageContainerName; } + + /// Backing field for property. + private string _vmwareFabricArmId; + + /// Gets or sets the ARM Id of the source VMware fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VmwareFabricArmId { get => this._vmwareFabricArmId; set => this._vmwareFabricArmId = value; } + + /// Backing field for property. + private string _vmwareSiteId; + + /// Gets or sets the ARM Id of the VMware site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VmwareSiteId { get => this._vmwareSiteId; } + + /// + /// Creates an new instance. + /// + public VMwareToAzStackHcireplicationExtensionModelCustomProperties() + { + this.__replicationExtensionModelCustomProperties.InstanceType = "VMwareToAzStackHCI"; + } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__replicationExtensionModelCustomProperties), __replicationExtensionModelCustomProperties); + await eventListener.AssertObjectIsValid(nameof(__replicationExtensionModelCustomProperties), __replicationExtensionModelCustomProperties); + } + } + /// VMware to AzStackHCI Replication extension model custom properties. + public partial interface IVMwareToAzStackHcireplicationExtensionModelCustomProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomProperties + { + /// Gets or sets the Uri of ASR. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Uri of ASR.", + SerializedName = @"asrServiceUri", + PossibleTypes = new [] { typeof(string) })] + string AsrServiceUri { get; } + /// Gets or sets the ARM Id of the target AzStackHCI fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the target AzStackHCI fabric.", + SerializedName = @"azStackHciFabricArmId", + PossibleTypes = new [] { typeof(string) })] + string AzStackHciFabricArmId { get; set; } + /// Gets or sets the ARM Id of the AzStackHCI site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the ARM Id of the AzStackHCI site.", + SerializedName = @"azStackHciSiteId", + PossibleTypes = new [] { typeof(string) })] + string AzStackHciSiteId { get; } + /// Gets or sets the Uri of Gateway. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Uri of Gateway.", + SerializedName = @"gatewayServiceUri", + PossibleTypes = new [] { typeof(string) })] + string GatewayServiceUri { get; } + /// Gets or sets the Uri of Rcm. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Uri of Rcm.", + SerializedName = @"rcmServiceUri", + PossibleTypes = new [] { typeof(string) })] + string RcmServiceUri { get; } + /// Gets or sets the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource group.", + SerializedName = @"resourceGroup", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroup { get; } + /// Gets or sets the resource location. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the resource location.", + SerializedName = @"resourceLocation", + PossibleTypes = new [] { typeof(string) })] + string ResourceLocation { get; } + /// Gets or sets the gateway service Id of source. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the gateway service Id of source.", + SerializedName = @"sourceGatewayServiceId", + PossibleTypes = new [] { typeof(string) })] + string SourceGatewayServiceId { get; } + /// Gets or sets the source storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the source storage container name.", + SerializedName = @"sourceStorageContainerName", + PossibleTypes = new [] { typeof(string) })] + string SourceStorageContainerName { get; } + /// Gets or sets the storage account Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the storage account Id.", + SerializedName = @"storageAccountId", + PossibleTypes = new [] { typeof(string) })] + string StorageAccountId { get; set; } + /// Gets or sets the Sas Secret of storage account. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the Sas Secret of storage account.", + SerializedName = @"storageAccountSasSecretName", + PossibleTypes = new [] { typeof(string) })] + string StorageAccountSasSecretName { get; set; } + /// Gets or sets the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; } + /// Gets or sets the gateway service Id of target. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the gateway service Id of target.", + SerializedName = @"targetGatewayServiceId", + PossibleTypes = new [] { typeof(string) })] + string TargetGatewayServiceId { get; } + /// Gets or sets the target storage container name. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the target storage container name.", + SerializedName = @"targetStorageContainerName", + PossibleTypes = new [] { typeof(string) })] + string TargetStorageContainerName { get; } + /// Gets or sets the ARM Id of the source VMware fabric. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the ARM Id of the source VMware fabric.", + SerializedName = @"vmwareFabricArmId", + PossibleTypes = new [] { typeof(string) })] + string VmwareFabricArmId { get; set; } + /// Gets or sets the ARM Id of the VMware site. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the ARM Id of the VMware site.", + SerializedName = @"vmwareSiteId", + PossibleTypes = new [] { typeof(string) })] + string VmwareSiteId { get; } + + } + /// VMware to AzStackHCI Replication extension model custom properties. + internal partial interface IVMwareToAzStackHcireplicationExtensionModelCustomPropertiesInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModelCustomPropertiesInternal + { + /// Gets or sets the Uri of ASR. + string AsrServiceUri { get; set; } + /// Gets or sets the ARM Id of the target AzStackHCI fabric. + string AzStackHciFabricArmId { get; set; } + /// Gets or sets the ARM Id of the AzStackHCI site. + string AzStackHciSiteId { get; set; } + /// Gets or sets the Uri of Gateway. + string GatewayServiceUri { get; set; } + /// Gets or sets the Uri of Rcm. + string RcmServiceUri { get; set; } + /// Gets or sets the resource group. + string ResourceGroup { get; set; } + /// Gets or sets the resource location. + string ResourceLocation { get; set; } + /// Gets or sets the gateway service Id of source. + string SourceGatewayServiceId { get; set; } + /// Gets or sets the source storage container name. + string SourceStorageContainerName { get; set; } + /// Gets or sets the storage account Id. + string StorageAccountId { get; set; } + /// Gets or sets the Sas Secret of storage account. + string StorageAccountSasSecretName { get; set; } + /// Gets or sets the subscription. + string SubscriptionId { get; set; } + /// Gets or sets the gateway service Id of target. + string TargetGatewayServiceId { get; set; } + /// Gets or sets the target storage container name. + string TargetStorageContainerName { get; set; } + /// Gets or sets the ARM Id of the source VMware fabric. + string VmwareFabricArmId { get; set; } + /// Gets or sets the ARM Id of the VMware site. + string VmwareSiteId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.json.cs new file mode 100644 index 00000000000..29b21025177 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VMwareToAzStackHcireplicationExtensionModelCustomProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// VMware to AzStackHCI Replication extension model custom properties. + public partial class VMwareToAzStackHcireplicationExtensionModelCustomProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVMwareToAzStackHcireplicationExtensionModelCustomProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VMwareToAzStackHcireplicationExtensionModelCustomProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __replicationExtensionModelCustomProperties?.ToJson(container, serializationMode); + AddIf( null != (((object)this._vmwareFabricArmId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._vmwareFabricArmId.ToString()) : null, "vmwareFabricArmId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._vmwareSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._vmwareSiteId.ToString()) : null, "vmwareSiteId" ,container.Add ); + } + AddIf( null != (((object)this._azStackHciFabricArmId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._azStackHciFabricArmId.ToString()) : null, "azStackHciFabricArmId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._azStackHciSiteId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._azStackHciSiteId.ToString()) : null, "azStackHciSiteId" ,container.Add ); + } + AddIf( null != (((object)this._storageAccountId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageAccountId.ToString()) : null, "storageAccountId" ,container.Add ); + AddIf( null != (((object)this._storageAccountSasSecretName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._storageAccountSasSecretName.ToString()) : null, "storageAccountSasSecretName" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._asrServiceUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._asrServiceUri.ToString()) : null, "asrServiceUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._rcmServiceUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._rcmServiceUri.ToString()) : null, "rcmServiceUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._gatewayServiceUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._gatewayServiceUri.ToString()) : null, "gatewayServiceUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceGatewayServiceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceGatewayServiceId.ToString()) : null, "sourceGatewayServiceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetGatewayServiceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetGatewayServiceId.ToString()) : null, "targetGatewayServiceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._sourceStorageContainerName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._sourceStorageContainerName.ToString()) : null, "sourceStorageContainerName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._targetStorageContainerName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._targetStorageContainerName.ToString()) : null, "targetStorageContainerName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceLocation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceLocation.ToString()) : null, "resourceLocation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resourceGroup)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._resourceGroup.ToString()) : null, "resourceGroup" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VMwareToAzStackHcireplicationExtensionModelCustomProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __replicationExtensionModelCustomProperties = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModelCustomProperties(json); + {_vmwareFabricArmId = If( json?.PropertyT("vmwareFabricArmId"), out var __jsonVmwareFabricArmId) ? (string)__jsonVmwareFabricArmId : (string)_vmwareFabricArmId;} + {_vmwareSiteId = If( json?.PropertyT("vmwareSiteId"), out var __jsonVmwareSiteId) ? (string)__jsonVmwareSiteId : (string)_vmwareSiteId;} + {_azStackHciFabricArmId = If( json?.PropertyT("azStackHciFabricArmId"), out var __jsonAzStackHciFabricArmId) ? (string)__jsonAzStackHciFabricArmId : (string)_azStackHciFabricArmId;} + {_azStackHciSiteId = If( json?.PropertyT("azStackHciSiteId"), out var __jsonAzStackHciSiteId) ? (string)__jsonAzStackHciSiteId : (string)_azStackHciSiteId;} + {_storageAccountId = If( json?.PropertyT("storageAccountId"), out var __jsonStorageAccountId) ? (string)__jsonStorageAccountId : (string)_storageAccountId;} + {_storageAccountSasSecretName = If( json?.PropertyT("storageAccountSasSecretName"), out var __jsonStorageAccountSasSecretName) ? (string)__jsonStorageAccountSasSecretName : (string)_storageAccountSasSecretName;} + {_asrServiceUri = If( json?.PropertyT("asrServiceUri"), out var __jsonAsrServiceUri) ? (string)__jsonAsrServiceUri : (string)_asrServiceUri;} + {_rcmServiceUri = If( json?.PropertyT("rcmServiceUri"), out var __jsonRcmServiceUri) ? (string)__jsonRcmServiceUri : (string)_rcmServiceUri;} + {_gatewayServiceUri = If( json?.PropertyT("gatewayServiceUri"), out var __jsonGatewayServiceUri) ? (string)__jsonGatewayServiceUri : (string)_gatewayServiceUri;} + {_sourceGatewayServiceId = If( json?.PropertyT("sourceGatewayServiceId"), out var __jsonSourceGatewayServiceId) ? (string)__jsonSourceGatewayServiceId : (string)_sourceGatewayServiceId;} + {_targetGatewayServiceId = If( json?.PropertyT("targetGatewayServiceId"), out var __jsonTargetGatewayServiceId) ? (string)__jsonTargetGatewayServiceId : (string)_targetGatewayServiceId;} + {_sourceStorageContainerName = If( json?.PropertyT("sourceStorageContainerName"), out var __jsonSourceStorageContainerName) ? (string)__jsonSourceStorageContainerName : (string)_sourceStorageContainerName;} + {_targetStorageContainerName = If( json?.PropertyT("targetStorageContainerName"), out var __jsonTargetStorageContainerName) ? (string)__jsonTargetStorageContainerName : (string)_targetStorageContainerName;} + {_resourceLocation = If( json?.PropertyT("resourceLocation"), out var __jsonResourceLocation) ? (string)__jsonResourceLocation : (string)_resourceLocation;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_resourceGroup = If( json?.PropertyT("resourceGroup"), out var __jsonResourceGroup) ? (string)__jsonResourceGroup : (string)_resourceGroup;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.PowerShell.cs new file mode 100644 index 00000000000..04b1eee2203 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Vault model. + [System.ComponentModel.TypeConverter(typeof(VaultIdentityModelTypeConverter))] + public partial class VaultIdentityModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVaultIdentityModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultIdentityModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultIdentityModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultIdentityModel(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.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).TenantId, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultIdentityModel(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.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)this).TenantId, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// Vault model. + [System.ComponentModel.TypeConverter(typeof(VaultIdentityModelTypeConverter))] + public partial interface IVaultIdentityModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.TypeConverter.cs new file mode 100644 index 00000000000..42278b253bd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultIdentityModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVaultIdentityModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultIdentityModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultIdentityModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultIdentityModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.cs new file mode 100644 index 00000000000..a6171058972 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault model. + public partial class VaultIdentityModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// + /// Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access + /// to an Azure resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Backing field for property. + private string _tenantId; + + /// + /// Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the identityType which can be either SystemAssigned or None. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public VaultIdentityModel() + { + + } + } + /// Vault model. + public partial interface IVaultIdentityModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// + /// Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access + /// to an Azure resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access to an Azure resource.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// + /// Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + /// Gets or sets the identityType which can be either SystemAssigned or None. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the identityType which can be either SystemAssigned or None.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned")] + string Type { get; set; } + + } + /// Vault model. + internal partial interface IVaultIdentityModelInternal + + { + /// + /// Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access + /// to an Azure resource. + /// + string PrincipalId { get; set; } + /// + /// Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + /// + string TenantId { get; set; } + /// Gets or sets the identityType which can be either SystemAssigned or None. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.json.cs new file mode 100644 index 00000000000..f7ee8e4abe6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultIdentityModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault model. + public partial class VaultIdentityModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VaultIdentityModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VaultIdentityModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)_principalId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)_tenantId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.PowerShell.cs new file mode 100644 index 00000000000..e70d0643a14 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.PowerShell.cs @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Vault model. + [System.ComponentModel.TypeConverter(typeof(VaultModelTypeConverter))] + public partial class VaultModel + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVaultModel DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultModel(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultModel(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultModel(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.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("VaultType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).VaultType = (string) content.GetValueForProperty("VaultType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).VaultType, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultModel(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.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("VaultType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).VaultType = (string) content.GetValueForProperty("VaultType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).VaultType, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + AfterDeserializePSObject(content); + } + } + /// Vault model. + [System.ComponentModel.TypeConverter(typeof(VaultModelTypeConverter))] + public partial interface IVaultModel + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.TypeConverter.cs new file mode 100644 index 00000000000..4cf62b15bcd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultModelTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVaultModel ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultModel.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultModel.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultModel.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VaultModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.cs new file mode 100644 index 00000000000..3c6dd490168 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.cs @@ -0,0 +1,312 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault model. + public partial class VaultModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ServiceResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelInternal.ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ServiceResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ServiceResourceId = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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); } + + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ServiceResourceId; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IResourceInternal)__trackedResource).Type; } + + /// Gets or sets the type of vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string VaultType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).VaultType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).VaultType = value ?? null; } + + /// 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.RecoveryServicesDataReplication.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + + /// Creates an new instance. + public VaultModel() + { + + } + } + /// Vault model. + public partial interface IVaultModel : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Gets or sets the provisioning state of the vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the vault.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service resource Id.", + SerializedName = @"serviceResourceId", + PossibleTypes = new [] { typeof(string) })] + string ServiceResourceId { get; } + /// Gets or sets the type of vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of vault.", + SerializedName = @"vaultType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + string VaultType { get; set; } + + } + /// Vault model. + internal partial interface IVaultModelInternal : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceInternal + { + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the vault. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the service resource Id. + string ServiceResourceId { get; set; } + /// Gets or sets the type of vault. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + string VaultType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.json.cs new file mode 100644 index 00000000000..855b73eb7e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModel.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault model. + public partial class VaultModel + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VaultModel(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VaultModel(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelProperties.FromJson(__jsonProperties) : _property;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.PowerShell.cs new file mode 100644 index 00000000000..70cb5675c7e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// The response of a VaultModel list operation. + [System.ComponentModel.TypeConverter(typeof(VaultModelListResultTypeConverter))] + public partial class VaultModelListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVaultModelListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultModelListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultModelListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultModelListResult(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.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)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 VaultModelListResult(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.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The response of a VaultModel list operation. + [System.ComponentModel.TypeConverter(typeof(VaultModelListResultTypeConverter))] + public partial interface IVaultModelListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.TypeConverter.cs new file mode 100644 index 00000000000..dccde9a5afc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultModelListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVaultModelListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultModelListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultModelListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultModelListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.cs new file mode 100644 index 00000000000..8b2009b0d42 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a VaultModel list operation. + public partial class VaultModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The VaultModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public VaultModelListResult() + { + + } + } + /// The response of a VaultModel list operation. + public partial interface IVaultModelListResult : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 VaultModel items on this page + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The VaultModel items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a VaultModel list operation. + internal partial interface IVaultModelListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The VaultModel items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.json.cs new file mode 100644 index 00000000000..97a4c45cbb4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelListResult.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// The response of a VaultModel list operation. + public partial class VaultModelListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VaultModelListResult(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VaultModelListResult(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel) (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.PowerShell.cs new file mode 100644 index 00000000000..642895a7b50 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Vault properties. + [System.ComponentModel.TypeConverter(typeof(VaultModelPropertiesTypeConverter))] + public partial class VaultModelProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVaultModelProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultModelProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultModelProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultModelProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("VaultType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).VaultType = (string) content.GetValueForProperty("VaultType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).VaultType, 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 VaultModelProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("VaultType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).VaultType = (string) content.GetValueForProperty("VaultType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)this).VaultType, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// Vault properties. + [System.ComponentModel.TypeConverter(typeof(VaultModelPropertiesTypeConverter))] + public partial interface IVaultModelProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.TypeConverter.cs new file mode 100644 index 00000000000..83839a8782a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultModelPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVaultModelProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultModelProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultModelProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultModelProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.cs new file mode 100644 index 00000000000..07bac0386ba --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault properties. + public partial class VaultModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal + { + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for ServiceResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal.ServiceResourceId { get => this._serviceResourceId; set { {_serviceResourceId = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Gets or sets the provisioning state of the vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _serviceResourceId; + + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string ServiceResourceId { get => this._serviceResourceId; } + + /// Backing field for property. + private string _vaultType; + + /// Gets or sets the type of vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string VaultType { get => this._vaultType; set => this._vaultType = value; } + + /// Creates an new instance. + public VaultModelProperties() + { + + } + } + /// Vault properties. + public partial interface IVaultModelProperties : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the provisioning state of the vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the vault.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service resource Id.", + SerializedName = @"serviceResourceId", + PossibleTypes = new [] { typeof(string) })] + string ServiceResourceId { get; } + /// Gets or sets the type of vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of vault.", + SerializedName = @"vaultType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + string VaultType { get; set; } + + } + /// Vault properties. + internal partial interface IVaultModelPropertiesInternal + + { + /// Gets or sets the provisioning state of the vault. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the service resource Id. + string ServiceResourceId { get; set; } + /// Gets or sets the type of vault. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + string VaultType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.json.cs new file mode 100644 index 00000000000..b6b4356b9c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelProperties.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault properties. + public partial class VaultModelProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VaultModelProperties(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._serviceResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._serviceResourceId.ToString()) : null, "serviceResourceId" ,container.Add ); + } + AddIf( null != (((object)this._vaultType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._vaultType.ToString()) : null, "vaultType" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VaultModelProperties(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_serviceResourceId = If( json?.PropertyT("serviceResourceId"), out var __jsonServiceResourceId) ? (string)__jsonServiceResourceId : (string)_serviceResourceId;} + {_vaultType = If( json?.PropertyT("vaultType"), out var __jsonVaultType) ? (string)__jsonVaultType : (string)_vaultType;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.PowerShell.cs new file mode 100644 index 00000000000..a49a30b259d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.PowerShell.cs @@ -0,0 +1,308 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Vault model update. + [System.ComponentModel.TypeConverter(typeof(VaultModelUpdateTypeConverter))] + public partial class VaultModelUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVaultModelUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultModelUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultModelUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultModelUpdate(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.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultIdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelUpdateTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("VaultType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).VaultType = (string) content.GetValueForProperty("VaultType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).VaultType, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)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.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)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 VaultModelUpdate(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.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultIdentityModelTypeConverter.ConvertFrom); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelUpdateTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("ServiceResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ServiceResourceId = (string) content.GetValueForProperty("ServiceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).ServiceResourceId, global::System.Convert.ToString); + } + if (content.Contains("VaultType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).VaultType = (string) content.GetValueForProperty("VaultType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).VaultType, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)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.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + } + /// Vault model update. + [System.ComponentModel.TypeConverter(typeof(VaultModelUpdateTypeConverter))] + public partial interface IVaultModelUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.TypeConverter.cs new file mode 100644 index 00000000000..25c12ca362f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultModelUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVaultModelUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultModelUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultModelUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultModelUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.cs new file mode 100644 index 00000000000..651246979b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.cs @@ -0,0 +1,416 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault model update. + public partial class VaultModelUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal + { + + /// Backing field for property. + private string _id; + + /// Gets or sets the Id of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel _identity; + + /// Vault identity. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultIdentityModel()); set => this._identity = value; } + + /// + /// Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access + /// to an Azure resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).PrincipalId; } + + /// + /// Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).TenantId; } + + /// Gets or sets the identityType which can be either SystemAssigned or None. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).Type = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultIdentityModel()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModelInternal)Identity).TenantId = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for ServiceResourceId + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ServiceResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ServiceResourceId = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Gets or sets the name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties _property; + + /// Vault properties. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelProperties()); set => this._property = value; } + + /// Gets or sets the provisioning state of the vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ProvisioningState; } + + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string ServiceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).ServiceResourceId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData _systemData; + + /// Metadata pertaining to creation and last modification of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags _tag; + + /// Gets or sets the resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelUpdateTags()); set => this._tag = value; } + + /// Backing field for property. + private string _type; + + /// Gets or sets the type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Gets or sets the type of vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Origin(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PropertyOrigin.Inlined)] + public string VaultType { get => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).VaultType; set => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelPropertiesInternal)Property).VaultType = value ?? null; } + + /// Creates an new instance. + public VaultModelUpdate() + { + + } + } + /// Vault model update. + public partial interface IVaultModelUpdate : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable + { + /// Gets or sets the Id of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the Id of the resource.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// + /// Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access + /// to an Azure resource. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access to an Azure resource.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string IdentityPrincipalId { get; } + /// + /// Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + /// + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string IdentityTenantId { get; } + /// Gets or sets the identityType which can be either SystemAssigned or None. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the identityType which can be either SystemAssigned or None.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned")] + string IdentityType { get; set; } + /// Gets or sets the name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the name of the resource.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Gets or sets the provisioning state of the vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the provisioning state of the vault.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + /// Gets or sets the service resource Id. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the service resource Id.", + SerializedName = @"serviceResourceId", + PossibleTypes = new [] { typeof(string) })] + string ServiceResourceId { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// Gets or sets the resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags) })] + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags Tag { get; set; } + /// Gets or sets the type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Gets or sets the type of the resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + /// Gets or sets the type of vault. + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Gets or sets the type of vault.", + SerializedName = @"vaultType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + string VaultType { get; set; } + + } + /// Vault model update. + internal partial interface IVaultModelUpdateInternal + + { + /// Gets or sets the Id of the resource. + string Id { get; set; } + /// Vault identity. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultIdentityModel Identity { get; set; } + /// + /// Gets or sets the object ID of the service principal object for the managed identity that is used to grant role-based access + /// to an Azure resource. + /// + string IdentityPrincipalId { get; set; } + /// + /// Gets or sets a Globally Unique Identifier (GUID) that represents the Azure AD tenant where the resource is now a member. + /// + string IdentityTenantId { get; set; } + /// Gets or sets the identityType which can be either SystemAssigned or None. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned")] + string IdentityType { get; set; } + /// Gets or sets the name of the resource. + string Name { get; set; } + /// Vault properties. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelProperties Property { get; set; } + /// Gets or sets the provisioning state of the vault. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("Canceled", "Creating", "Deleting", "Deleted", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + /// Gets or sets the service resource Id. + string ServiceResourceId { get; set; } + /// Metadata pertaining to creation and last modification of the resource. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// Gets or sets the resource tags. + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags Tag { get; set; } + /// Gets or sets the type of the resource. + string Type { get; set; } + /// Gets or sets the type of vault. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + string VaultType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.json.cs new file mode 100644 index 00000000000..077345e7bbb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdate.json.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Vault model update. + public partial class VaultModelUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VaultModelUpdate(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + internal VaultModelUpdate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.VaultModelProperties.FromJson(__jsonProperties) : _property;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultIdentityModel.FromJson(__jsonIdentity) : _identity;} + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModelUpdateTags.FromJson(__jsonTags) : _tag;} + {_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); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.PowerShell.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.PowerShell.cs new file mode 100644 index 00000000000..8be472ebee2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.PowerShell.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// Gets or sets the resource tags. + [System.ComponentModel.TypeConverter(typeof(VaultModelUpdateTagsTypeConverter))] + public partial class VaultModelUpdateTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultModelUpdateTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultModelUpdateTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 VaultModelUpdateTags(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 VaultModelUpdateTags(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); + } + } + /// Gets or sets the resource tags. + [System.ComponentModel.TypeConverter(typeof(VaultModelUpdateTagsTypeConverter))] + public partial interface IVaultModelUpdateTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.TypeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.TypeConverter.cs new file mode 100644 index 00000000000..51a22af96db --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultModelUpdateTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultModelUpdateTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultModelUpdateTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultModelUpdateTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.cs new file mode 100644 index 00000000000..2bf29ea2e01 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Gets or sets the resource tags. + public partial class VaultModelUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTagsInternal + { + + /// Creates an new instance. + public VaultModelUpdateTags() + { + + } + } + /// Gets or sets the resource tags. + public partial interface IVaultModelUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + + } + /// Gets or sets the resource tags. + internal partial interface IVaultModelUpdateTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.dictionary.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.dictionary.cs new file mode 100644 index 00000000000..8c89a7980ea --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + public partial class VaultModelUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.VaultModelUpdateTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.json.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.json.cs new file mode 100644 index 00000000000..377eb1e0d76 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/api/Models/VaultModelUpdateTags.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.RecoveryServicesDataReplication.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + + /// Gets or sets the resource tags. + public partial class VaultModelUpdateTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModelUpdateTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject json ? new VaultModelUpdateTags(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.RecoveryServicesDataReplication.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonObject instance to deserialize from. + /// + internal VaultModelUpdateTags(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_Get.cs new file mode 100644 index 00000000000..554c91d98f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the alert configuration setting. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEmailConfiguration_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the alert configuration setting.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEmailConfiguration_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEmailConfiguration_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EmailConfigurationGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentity.cs new file mode 100644 index 00000000000..cae681c3732 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the alert configuration setting. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the alert configuration setting.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEmailConfiguration_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.EmailConfigurationGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.EmailConfigurationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.EmailConfigurationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.EmailConfigurationGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.EmailConfigurationName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..46c42fb634d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the alert configuration setting. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the alert configuration setting.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEmailConfiguration_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/alertSettings/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.EmailConfigurationGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.EmailConfigurationGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_List.cs new file mode 100644 index 00000000000..2c458ca9d23 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEmailConfiguration_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of alert configuration settings for the given vault. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEmailConfiguration_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of alert configuration settings for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEmailConfiguration_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEmailConfiguration_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EmailConfigurationList(SubscriptionId, ResourceGroupName, VaultName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EmailConfigurationList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_Get.cs new file mode 100644 index 00000000000..1e8c0a109b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the event. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events/{eventName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEvent_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the event.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events/{eventName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEvent_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The event name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The event name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The event name.", + SerializedName = @"eventName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EventName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEvent_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EventGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel + /// 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.RecoveryServicesDataReplication.Models.IEventModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_GetViaIdentity.cs new file mode 100644 index 00000000000..a77bc19e65b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the event. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events/{eventName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEvent_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the event.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events/{eventName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEvent_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEvent_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.EventGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.EventName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.EventName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.EventGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.EventName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel + /// 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.RecoveryServicesDataReplication.Models.IEventModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..6ca4793c4cb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the event. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events/{eventName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEvent_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the event.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events/{eventName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEvent_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The event name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The event name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The event name.", + SerializedName = @"eventName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EventName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEvent_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/events/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.EventGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.EventGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModel + /// 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.RecoveryServicesDataReplication.Models.IEventModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_List.cs new file mode 100644 index 00000000000..3e4789d3199 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationEvent_List.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of events in the given vault. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationEvent_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEventModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of events in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/events", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationEvent_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// Continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _odataOption; + + /// OData options. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "OData options.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"OData options.", + SerializedName = @"odataOptions", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string OdataOption { get => this._odataOption; set => this._odataOption = value; } + + /// Backing field for property. + private int _pageSize; + + /// Page size. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Page size.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Page size.", + SerializedName = @"pageSize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public int PageSize { get => this._pageSize; set => this._pageSize = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationEvent_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EventList(SubscriptionId, ResourceGroupName, VaultName, this.InvocationInformation.BoundParameters.ContainsKey("OdataOption") ? OdataOption : null, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, this.InvocationInformation.BoundParameters.ContainsKey("PageSize") ? PageSize : default(int?), onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,OdataOption=this.InvocationInformation.BoundParameters.ContainsKey("OdataOption") ? OdataOption : null,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null,PageSize=this.InvocationInformation.BoundParameters.ContainsKey("PageSize") ? PageSize : default(int?),VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEventModelListResult + /// 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.RecoveryServicesDataReplication.Models.IEventModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EventList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_Get.cs new file mode 100644 index 00000000000..b163d9c7527 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the replication extension. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationExtension_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the replication extension.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationExtension_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationExtension_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_GetViaIdentity.cs new file mode 100644 index 00000000000..3f3323868dc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the replication extension. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationExtension_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the replication extension.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationExtension_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationExtension_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ReplicationExtensionGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ReplicationExtensionName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ReplicationExtensionName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ReplicationExtensionGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ReplicationExtensionName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..d0720728084 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the replication extension. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationExtension_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the replication extension.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationExtension_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationExtension_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/replicationExtensions/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ReplicationExtensionGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ReplicationExtensionGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_List.cs new file mode 100644 index 00000000000..7fa032acdf9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationExtension_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of replication extensions in the given vault. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationExtension_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of replication extensions in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationExtension_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationExtension_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionList(SubscriptionId, ResourceGroupName, VaultName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_Get.cs new file mode 100644 index 00000000000..96408d9b7e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the fabric agent. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabricAgent_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabricAgent_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabricAgent_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentGet(SubscriptionId, ResourceGroupName, FabricName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentity.cs new file mode 100644 index 00000000000..32332b951f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the fabric agent. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabricAgent_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabricAgent_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FabricAgentGetViaIdentity(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.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FabricAgentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricAgentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FabricAgentGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, InputObject.FabricAgentName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentityReplicationFabric.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentityReplicationFabric.cs new file mode 100644 index 00000000000..2b9465941a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentityReplicationFabric.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the fabric agent. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabricAgent_GetViaIdentityReplicationFabric")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentityReplicationFabric : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationFabricInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationFabricInputObject { get => this._replicationFabricInputObject; set => this._replicationFabricInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabricAgent_GetViaIdentityReplicationFabric() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationFabricInputObject?.Id != null) + { + this.ReplicationFabricInputObject.Id += $"/fabricAgents/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.FabricAgentGetViaIdentity(ReplicationFabricInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationFabricInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + if (null == ReplicationFabricInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + if (null == ReplicationFabricInputObject.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + await this.Client.FabricAgentGet(ReplicationFabricInputObject.SubscriptionId ?? null, ReplicationFabricInputObject.ResourceGroupName ?? null, ReplicationFabricInputObject.FabricName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_List.cs new file mode 100644 index 00000000000..db89061fa6d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabricAgent_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of fabric agents in the given fabric. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabricAgent_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of fabric agents in the given fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabricAgent_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabricAgent_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentList(SubscriptionId, ResourceGroupName, FabricName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_Get.cs new file mode 100644 index 00000000000..b3620605b84 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the fabric. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabric_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabric_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_GetViaIdentity.cs new file mode 100644 index 00000000000..127059b92ec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the fabric. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabric_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabric_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FabricGetViaIdentity(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.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FabricGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_List.cs new file mode 100644 index 00000000000..a0928dd5998 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of fabrics in the given subscription and resource group. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabric_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of fabrics in the given subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabric_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// Continuation token from the previous call. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Continuation token from the previous call.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Continuation token from the previous call.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricList(SubscriptionId, ResourceGroupName, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModelListResult + /// 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.RecoveryServicesDataReplication.Models.IFabricModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_List1.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_List1.cs new file mode 100644 index 00000000000..8a8a3cff597 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of fabrics in the given subscription. + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationFabrics" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationFabric_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of fabrics in the given subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationFabrics", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationFabric_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationFabric_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModelListResult + /// 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.RecoveryServicesDataReplication.Models.IFabricModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_Get.cs new file mode 100644 index 00000000000..4eb46e47db8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the job. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationJob_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the job.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationJob_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The job name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The job name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The job name.", + SerializedName = @"jobName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("JobName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationJob_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.JobGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel + /// 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.RecoveryServicesDataReplication.Models.IJobModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_GetViaIdentity.cs new file mode 100644 index 00000000000..f3c943c1859 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the job. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationJob_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the job.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationJob_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationJob_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.JobGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.JobName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.JobName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.JobGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.JobName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel + /// 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.RecoveryServicesDataReplication.Models.IJobModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..b5db39017b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the job. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationJob_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the job.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs/{jobName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationJob_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The job name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The job name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The job name.", + SerializedName = @"jobName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("JobName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationJob_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/jobs/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.JobGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.JobGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModel + /// 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.RecoveryServicesDataReplication.Models.IJobModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_List.cs new file mode 100644 index 00000000000..d355fadba71 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationJob_List.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of jobs in the given vault. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationJob_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IJobModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of jobs in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/jobs", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationJob_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// Continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _odataOption; + + /// OData options. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "OData options.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"OData options.", + SerializedName = @"odataOptions", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string OdataOption { get => this._odataOption; set => this._odataOption = value; } + + /// Backing field for property. + private int _pageSize; + + /// Page size. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Page size.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Page size.", + SerializedName = @"pageSize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public int PageSize { get => this._pageSize; set => this._pageSize = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationJob_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.JobList(SubscriptionId, ResourceGroupName, VaultName, this.InvocationInformation.BoundParameters.ContainsKey("OdataOption") ? OdataOption : null, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, this.InvocationInformation.BoundParameters.ContainsKey("PageSize") ? PageSize : default(int?), onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,OdataOption=this.InvocationInformation.BoundParameters.ContainsKey("OdataOption") ? OdataOption : null,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null,PageSize=this.InvocationInformation.BoundParameters.ContainsKey("PageSize") ? PageSize : default(int?),VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IJobModelListResult + /// 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.RecoveryServicesDataReplication.Models.IJobModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.JobList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_Get.cs new file mode 100644 index 00000000000..95c857c476f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the location based operation result. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationLocationBasedOperationResult_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the location based operation result.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _operationId; + + /// The ID of an ongoing async operation. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of an ongoing async operation.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of an ongoing async operation.", + SerializedName = @"operationId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string OperationId { get => this._operationId; set => this._operationId = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.LocationBasedOperationResultsGet(SubscriptionId, ResourceGroupName, Location, OperationId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,Location=Location,OperationId=OperationId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Models.IOperationStatus + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentity.cs new file mode 100644 index 00000000000..fb04478524e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the location based operation result. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the location based operation result.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.LocationBasedOperationResultsGetViaIdentity(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.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.OperationId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OperationId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.LocationBasedOperationResultsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.Location ?? null, InputObject.OperationId ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Models.IOperationStatus + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentityLocation.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentityLocation.cs new file mode 100644 index 00000000000..9b2fb3c2290 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentityLocation.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the location based operation result. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentityLocation")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the location based operation result.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/locations/{location}/operationResults/{operationId}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentityLocation : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _locationInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity LocationInputObject { get => this._locationInputObject; set => this._locationInputObject = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _operationId; + + /// The ID of an ongoing async operation. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of an ongoing async operation.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of an ongoing async operation.", + SerializedName = @"operationId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string OperationId { get => this._operationId; set => this._operationId = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationLocationBasedOperationResult_GetViaIdentityLocation() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (LocationInputObject?.Id != null) + { + this.LocationInputObject.Id += $"/operationResults/{(global::System.Uri.EscapeDataString(this.OperationId.ToString()))}"; + await this.Client.LocationBasedOperationResultsGetViaIdentity(LocationInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == LocationInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + if (null == LocationInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + if (null == LocationInputObject.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("LocationInputObject has null value for LocationInputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, LocationInputObject) ); + } + await this.Client.LocationBasedOperationResultsGet(LocationInputObject.SubscriptionId ?? null, LocationInputObject.ResourceGroupName ?? null, LocationInputObject.Location ?? null, OperationId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { OperationId=OperationId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Models.IOperationStatus + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperationResult_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperationResult_Get.cs new file mode 100644 index 00000000000..22b6ec858ec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperationResult_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the operations. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/operationResults/{operationId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationOperationResult_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the operations.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/operationResults/{operationId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationOperationResult_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _operationId; + + /// The ID of an ongoing async operation. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of an ongoing async operation.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of an ongoing async operation.", + SerializedName = @"operationId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string OperationId { get => this._operationId; set => this._operationId = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationOperationResult_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationResultsGet(SubscriptionId, ResourceGroupName, OperationId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,OperationId=OperationId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Models.IOperationStatus + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperationResult_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperationResult_GetViaIdentity.cs new file mode 100644 index 00000000000..12197130b01 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperationResult_GetViaIdentity.cs @@ -0,0 +1,484 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the operations. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/operationResults/{operationId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationOperationResult_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperationStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the operations.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/operationResults/{operationId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/{operationId}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationOperationResult_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationOperationResult_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OperationResultsGetViaIdentity(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.OperationId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OperationId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OperationResultsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OperationId ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IOperationStatus + /// 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.RecoveryServicesDataReplication.Models.IOperationStatus + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperation_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperation_List.cs new file mode 100644 index 00000000000..6cfe731d9de --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationOperation_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Microsoft.DataReplication/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/providers/Microsoft.DataReplication/operations", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationOperation_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_Get.cs new file mode 100644 index 00000000000..07cb60a5169 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the policy. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPolicy_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPolicy_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPolicy_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentity.cs new file mode 100644 index 00000000000..658e4389713 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the policy. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPolicy_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPolicy_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PolicyGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PolicyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PolicyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PolicyGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PolicyName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..ace0bda7e69 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the policy. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPolicy_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPolicy_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/replicationPolicies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.PolicyGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.PolicyGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_List.cs new file mode 100644 index 00000000000..08ec7daf97c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPolicy_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of policies in the given vault. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPolicy_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of policies in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPolicy_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPolicy_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyList(SubscriptionId, ResourceGroupName, VaultName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModelListResult + /// 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.RecoveryServicesDataReplication.Models.IPolicyModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Get.cs new file mode 100644 index 00000000000..1c1ad05d99b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the private endpoint connection proxy details. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the private endpoint connection proxy details.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentity.cs new file mode 100644 index 00000000000..5518d8fbb64 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the private endpoint connection proxy details. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the private endpoint connection proxy details.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PrivateEndpointConnectionProxiesGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PrivateEndpointConnectionProxyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PrivateEndpointConnectionProxyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PrivateEndpointConnectionProxyName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..ffb934dab77 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the private endpoint connection proxy details. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the private endpoint connection proxy details.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/privateEndpointConnectionProxies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.PrivateEndpointConnectionProxiesGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_List.cs new file mode 100644 index 00000000000..2510986bc6d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_List.cs @@ -0,0 +1,533 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the all private endpoint connections proxies. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the all private endpoint connections proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesList(SubscriptionId, ResourceGroupName, VaultName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxyListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_Get.cs new file mode 100644 index 00000000000..43ce52f0d1a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_Get.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationProtectedItem_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationProtectedItem_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationProtectedItem_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemGet(SubscriptionId, ResourceGroupName, VaultName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentity.cs new file mode 100644 index 00000000000..553498ec92b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentity.cs @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationProtectedItem_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationProtectedItem_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProtectedItemGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProtectedItemGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ProtectedItemName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..f0a442bf60c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentityReplicationVault.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationProtectedItem_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationProtectedItem_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/protectedItems/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ProtectedItemGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ProtectedItemGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_List.cs new file mode 100644 index 00000000000..f1858d62f1e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationProtectedItem_List.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of protected items in the given vault. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationProtectedItem_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of protected items in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationProtectedItem_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// Continuation token. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Continuation token.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Continuation token.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _odataOption; + + /// OData options. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "OData options.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"OData options.", + SerializedName = @"odataOptions", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string OdataOption { get => this._odataOption; set => this._odataOption = value; } + + /// Backing field for property. + private int _pageSize; + + /// Page size. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Page size.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Page size.", + SerializedName = @"pageSize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public int PageSize { get => this._pageSize; set => this._pageSize = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationProtectedItem_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemList(SubscriptionId, ResourceGroupName, VaultName, this.InvocationInformation.BoundParameters.ContainsKey("OdataOption") ? OdataOption : null, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, this.InvocationInformation.BoundParameters.ContainsKey("PageSize") ? PageSize : default(int?), onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,OdataOption=this.InvocationInformation.BoundParameters.ContainsKey("OdataOption") ? OdataOption : null,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null,PageSize=this.InvocationInformation.BoundParameters.ContainsKey("PageSize") ? PageSize : default(int?),VaultName=VaultName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_Get.cs new file mode 100644 index 00000000000..46eab48bb4b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_Get.cs @@ -0,0 +1,534 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the recovery point of a protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationRecoveryPoint_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the recovery point of a protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationRecoveryPoint_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The recovery point name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The recovery point name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The recovery point name.", + SerializedName = @"recoveryPointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("RecoveryPointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationRecoveryPoint_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.RecoveryPointGet(SubscriptionId, ResourceGroupName, VaultName, ProtectedItemName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,ProtectedItemName=ProtectedItemName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentity.cs new file mode 100644 index 00000000000..2dd99b751ab --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentity.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the recovery point of a protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the recovery point of a protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationRecoveryPoint_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.RecoveryPointGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.RecoveryPointName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.RecoveryPointName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.RecoveryPointGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ProtectedItemName ?? null, InputObject.RecoveryPointName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityProtectedItem.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityProtectedItem.cs new file mode 100644 index 00000000000..87280fe0ab2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityProtectedItem.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the recovery point of a protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityProtectedItem")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the recovery point of a protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityProtectedItem : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The recovery point name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The recovery point name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The recovery point name.", + SerializedName = @"recoveryPointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("RecoveryPointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _protectedItemInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ProtectedItemInputObject { get => this._protectedItemInputObject; set => this._protectedItemInputObject = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityProtectedItem() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ProtectedItemInputObject?.Id != null) + { + this.ProtectedItemInputObject.Id += $"/recoveryPoints/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.RecoveryPointGetViaIdentity(ProtectedItemInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ProtectedItemInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ProtectedItemInputObject has null value for ProtectedItemInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ProtectedItemInputObject) ); + } + if (null == ProtectedItemInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ProtectedItemInputObject has null value for ProtectedItemInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ProtectedItemInputObject) ); + } + if (null == ProtectedItemInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ProtectedItemInputObject has null value for ProtectedItemInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ProtectedItemInputObject) ); + } + if (null == ProtectedItemInputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ProtectedItemInputObject has null value for ProtectedItemInputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ProtectedItemInputObject) ); + } + await this.Client.RecoveryPointGet(ProtectedItemInputObject.SubscriptionId ?? null, ProtectedItemInputObject.ResourceGroupName ?? null, ProtectedItemInputObject.VaultName ?? null, ProtectedItemInputObject.ProtectedItemName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..3e8307ca02e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityReplicationVault.cs @@ -0,0 +1,514 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the recovery point of a protected item. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityReplicationVault")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the recovery point of a protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The recovery point name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The recovery point name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The recovery point name.", + SerializedName = @"recoveryPointName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("RecoveryPointName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationRecoveryPoint_GetViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/protectedItems/{(global::System.Uri.EscapeDataString(this.ProtectedItemName.ToString()))}/recoveryPoints/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.RecoveryPointGetViaIdentity(ReplicationVaultInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.RecoveryPointGet(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, ProtectedItemName, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProtectedItemName=ProtectedItemName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + /// 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.RecoveryServicesDataReplication.Models.IRecoveryPointModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_List.cs new file mode 100644 index 00000000000..05ffc290684 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationRecoveryPoint_List.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of recovery points of the given protected item. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationRecoveryPoint_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryPointModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of recovery points of the given protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/recoveryPoints", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationRecoveryPoint_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationRecoveryPoint_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.RecoveryPointList(SubscriptionId, ResourceGroupName, VaultName, ProtectedItemName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult + /// 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.RecoveryServicesDataReplication.Models.IRecoveryPointModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.RecoveryPointList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_Get.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_Get.cs new file mode 100644 index 00000000000..81a08d430fe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationVault_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationVault_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("VaultName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_GetViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_GetViaIdentity.cs new file mode 100644 index 00000000000..64d78efb7fa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the details of the vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationVault_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the details of the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationVault_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.VaultGetViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.VaultGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + 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/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_List.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_List.cs new file mode 100644 index 00000000000..732bfc5e2de --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of vaults in the given subscription and resource group. + /// + /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationVault_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of vaults in the given subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationVault_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _continuationToken; + + /// Continuation token from the previous call. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Continuation token from the previous call.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Continuation token from the previous call.", + SerializedName = @"continuationToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public string ContinuationToken { get => this._continuationToken; set => this._continuationToken = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultList(SubscriptionId, ResourceGroupName, this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,ContinuationToken=this.InvocationInformation.BoundParameters.ContainsKey("ContinuationToken") ? ContinuationToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModelListResult + /// 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.RecoveryServicesDataReplication.Models.IVaultModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_List1.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_List1.cs new file mode 100644 index 00000000000..d185d5d0043 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Gets the list of vaults in the given subscription. + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationVaults" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzRecoveryServicesDataReplicationVault_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Gets the list of vaults in the given subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/replicationVaults", ApiVersion = "2024-09-01")] + public partial class GetAzRecoveryServicesDataReplicationVault_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModelListResult + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 GetAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModelListResult + /// 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.RecoveryServicesDataReplication.Models.IVaultModelListResult + 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.RecoveryServicesDataReplication.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_Post.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_Post.cs new file mode 100644 index 00000000000..0aa743da09c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_Post.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Checks the resource name availability. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationCheckNameAvailability_Post", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Checks the resource name availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_Post : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel _body; + + /// Check name availability model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Check name availability model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Check name availability model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_Post() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CheckNameAvailabilityPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CheckNameAvailabilityPost(SubscriptionId, Location, Body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + 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/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostExpanded.cs new file mode 100644 index 00000000000..d2a8c207764 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostExpanded.cs @@ -0,0 +1,517 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Checks the resource name availability. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationCheckNameAvailability_PostExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Checks the resource name availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Check name availability model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.CheckNameAvailabilityModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Gets or sets the resource name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the resource 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Gets or sets the resource type. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the resource type.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + public string Type { get => _body.Type ?? null; set => _body.Type = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CheckNameAvailabilityPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CheckNameAvailabilityPost(SubscriptionId, Location, _body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + 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/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentity.cs new file mode 100644 index 00000000000..a2a75bb76f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentity.cs @@ -0,0 +1,497 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Checks the resource name availability. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Checks the resource name availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel _body; + + /// Check name availability model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Check name availability model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Check name availability model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentity() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CheckNameAvailabilityPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CheckNameAvailabilityPostViaIdentity(InputObject.Id, Body, 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.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CheckNameAvailabilityPost(InputObject.SubscriptionId ?? null, InputObject.Location ?? null, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + 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/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentityExpanded.cs new file mode 100644 index 00000000000..8457bf247a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentityExpanded.cs @@ -0,0 +1,508 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Checks the resource name availability. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Checks the resource name availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Check name availability model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.CheckNameAvailabilityModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Gets or sets the resource name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the resource 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Gets or sets the resource type. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the resource type.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + public string Type { get => _body.Type ?? null; set => _body.Type = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaIdentityExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CheckNameAvailabilityPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CheckNameAvailabilityPostViaIdentity(InputObject.Id, _body, 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.Location) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Location"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CheckNameAvailabilityPost(InputObject.SubscriptionId ?? null, InputObject.Location ?? null, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + 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/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonFilePath.cs new file mode 100644 index 00000000000..633d89e04df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonFilePath.cs @@ -0,0 +1,508 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Checks the resource name availability. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Checks the resource name availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Post operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Post operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Post 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; } } + + /// Backing field for property. + private string _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonFilePath() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CheckNameAvailabilityPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CheckNameAvailabilityPostViaJsonString(SubscriptionId, Location, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + 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/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonString.cs new file mode 100644 index 00000000000..16ba1450b96 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Checks the resource name availability. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Checks the resource name availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.DataReplication/locations/{location}/checkNameAvailability", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Post operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Post operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Post operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// Backing field for property. + private string _location; + + /// The name of the Azure region. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure region.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Azure region.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string Location { get => this._location; set => this._location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationCheckNameAvailability_PostViaJsonString() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CheckNameAvailabilityPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CheckNameAvailabilityPostViaJsonString(SubscriptionId, Location, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + /// 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.RecoveryServicesDataReplication.Models.ICheckNameAvailabilityResponseModel + 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/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_Post.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_Post.cs new file mode 100644 index 00000000000..5502485a24a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_Post.cs @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs resource deployment preflight validation. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationDeploymentPreflight_Post", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs resource deployment preflight validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_Post : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel _body; + + /// Deployment preflight model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Deployment preflight model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Deployment preflight model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _deploymentId; + + /// Deployment Id. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Deployment Id.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Deployment Id.", + SerializedName = @"deploymentId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string DeploymentId { get => this._deploymentId; set => this._deploymentId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_Post() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DeploymentPreflightPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DeploymentPreflightPost(SubscriptionId, ResourceGroupName, DeploymentId, Body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,DeploymentId=DeploymentId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / resources / + if (null != result.Resource) + { + if (0 == _responseSize && 1 == result.Resource.Count) + { + _firstResponse = result.Resource[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Resource ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostExpanded.cs new file mode 100644 index 00000000000..437a49dde85 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostExpanded.cs @@ -0,0 +1,528 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs resource deployment preflight validation. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationDeploymentPreflight_PostExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs resource deployment preflight validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Deployment preflight model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _deploymentId; + + /// Deployment Id. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Deployment Id.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Deployment Id.", + SerializedName = @"deploymentId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string DeploymentId { get => this._deploymentId; set => this._deploymentId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Gets or sets the list of resources. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of resources.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of resources.", + SerializedName = @"resources", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource[] Resource { get => _body.Resource?.ToArray() ?? null /* fixedArrayOf */; set => _body.Resource = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DeploymentPreflightPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DeploymentPreflightPost(SubscriptionId, ResourceGroupName, DeploymentId, _body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,DeploymentId=DeploymentId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / resources / + if (null != result.Resource) + { + if (0 == _responseSize && 1 == result.Resource.Count) + { + _firstResponse = result.Resource[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Resource ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentity.cs new file mode 100644 index 00000000000..14af5168682 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentity.cs @@ -0,0 +1,508 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs resource deployment preflight validation. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs resource deployment preflight validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel _body; + + /// Deployment preflight model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Deployment preflight model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Deployment preflight model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentity() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DeploymentPreflightPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.DeploymentPreflightPostViaIdentity(InputObject.Id, Body, 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.DeploymentId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DeploymentId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.DeploymentPreflightPost(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.DeploymentId ?? null, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / resources / + if (null != result.Resource) + { + if (0 == _responseSize && 1 == result.Resource.Count) + { + _firstResponse = result.Resource[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Resource ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentityExpanded.cs new file mode 100644 index 00000000000..b221d8db4be --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentityExpanded.cs @@ -0,0 +1,509 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs resource deployment preflight validation. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs resource deployment preflight validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Deployment preflight model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.DeploymentPreflightModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Gets or sets the list of resources. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of resources.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of resources.", + SerializedName = @"resources", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightResource[] Resource { get => _body.Resource?.ToArray() ?? null /* fixedArrayOf */; set => _body.Resource = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaIdentityExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DeploymentPreflightPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.DeploymentPreflightPostViaIdentity(InputObject.Id, _body, 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.DeploymentId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DeploymentId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.DeploymentPreflightPost(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.DeploymentId ?? null, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / resources / + if (null != result.Resource) + { + if (0 == _responseSize && 1 == result.Resource.Count) + { + _firstResponse = result.Resource[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Resource ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonFilePath.cs new file mode 100644 index 00000000000..e3bb1384b9d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonFilePath.cs @@ -0,0 +1,529 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs resource deployment preflight validation. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs resource deployment preflight validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _deploymentId; + + /// Deployment Id. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Deployment Id.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Deployment Id.", + SerializedName = @"deploymentId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string DeploymentId { get => this._deploymentId; set => this._deploymentId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Post operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Post operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Post 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonFilePath() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DeploymentPreflightPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DeploymentPreflightPostViaJsonString(SubscriptionId, ResourceGroupName, DeploymentId, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,DeploymentId=DeploymentId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / resources / + if (null != result.Resource) + { + if (0 == _responseSize && 1 == result.Resource.Count) + { + _firstResponse = result.Resource[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Resource ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonString.cs new file mode 100644 index 00000000000..972529a95e3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonString.cs @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs resource deployment preflight validation. + /// + /// [OpenAPI] Post=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs resource deployment preflight validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/deployments/{deploymentId}/preflight", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _deploymentId; + + /// Deployment Id. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Deployment Id.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Deployment Id.", + SerializedName = @"deploymentId", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string DeploymentId { get => this._deploymentId; set => this._deploymentId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Post operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Post operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Post 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationDeploymentPreflight_PostViaJsonString() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DeploymentPreflightPost' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DeploymentPreflightPostViaJsonString(SubscriptionId, ResourceGroupName, DeploymentId, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,DeploymentId=DeploymentId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + /// 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.RecoveryServicesDataReplication.Models.IDeploymentPreflightModel + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / resources / + if (null != result.Resource) + { + if (0 == _responseSize && 1 == result.Resource.Count) + { + _firstResponse = result.Resource[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Resource ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned.cs new file mode 100644 index 00000000000..4fe88c4d098 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel _body; + + /// Planned failover model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Planned failover model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Planned failover model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned(); + 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.VaultName = this.VaultName; + clone.ProtectedItemName = this.ProtectedItemName; + clone.Body = this.Body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_Planned() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemPlannedFailover(SubscriptionId, ResourceGroupName, VaultName, ProtectedItemName, Body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded.cs new file mode 100644 index 00000000000..69ed8c43d70 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Planned failover model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModel(); + + /// + /// 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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Discriminator property for PlannedFailoverModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Discriminator property for PlannedFailoverModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _body.CustomPropertyInstanceType ?? null; set => _body.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded(); + 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._body = this._body; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.VaultName = this.VaultName; + clone.ProtectedItemName = this.ProtectedItemName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemPlannedFailover(SubscriptionId, ResourceGroupName, VaultName, ProtectedItemName, _body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity.cs new file mode 100644 index 00000000000..64e3ecd863a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity.cs @@ -0,0 +1,556 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel _body; + + /// Planned failover model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Planned failover model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Planned failover model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity(); + 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.Body = this.Body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentity() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProtectedItemPlannedFailoverViaIdentity(InputObject.Id, Body, 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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProtectedItemPlannedFailover(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ProtectedItemName ?? null, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded.cs new file mode 100644 index 00000000000..4bc7eb9d8d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded.cs @@ -0,0 +1,556 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Planned failover model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModel(); + + /// + /// 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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Discriminator property for PlannedFailoverModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Discriminator property for PlannedFailoverModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _body.CustomPropertyInstanceType ?? null; set => _body.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded(); + 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._body = this._body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProtectedItemPlannedFailoverViaIdentity(InputObject.Id, _body, 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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProtectedItemPlannedFailover(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ProtectedItemName ?? null, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..69e9599cf9c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel _body; + + /// Planned failover model. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Planned failover model.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Planned failover model.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault(); + 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.ProtectedItemName = this.ProtectedItemName; + clone.Body = this.Body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVault() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/protectedItems/{(global::System.Uri.EscapeDataString(this.ProtectedItemName.ToString()))}"; + await this.Client.ProtectedItemPlannedFailoverViaIdentity(ReplicationVaultInputObject.Id, Body, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ProtectedItemPlannedFailover(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, ProtectedItemName, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..4fcdac6dc1f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Planned failover model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PlannedFailoverModel(); + + /// + /// 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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PlannedFailoverModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Discriminator property for PlannedFailoverModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Discriminator property for PlannedFailoverModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _body.CustomPropertyInstanceType ?? null; set => _body.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded(); + 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._body = this._body; + clone.ProtectedItemName = this.ProtectedItemName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaIdentityReplicationVaultExpanded() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/protectedItems/{(global::System.Uri.EscapeDataString(this.ProtectedItemName.ToString()))}"; + await this.Client.ProtectedItemPlannedFailoverViaIdentity(ReplicationVaultInputObject.Id, _body, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ProtectedItemPlannedFailover(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, ProtectedItemName, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath.cs new file mode 100644 index 00000000000..732aabbb867 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath.cs @@ -0,0 +1,591 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Planned operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Planned operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Planned 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath(); + 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.VaultName = this.VaultName; + clone.ProtectedItemName = this.ProtectedItemName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonFilePath() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemPlannedFailoverViaJsonString(SubscriptionId, ResourceGroupName, VaultName, ProtectedItemName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString.cs new file mode 100644 index 00000000000..5c8a0a84415 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs the planned failover on the protected item. + /// + /// [OpenAPI] PlannedFailover=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Invoke, @"AzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPlannedFailoverModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs the planned failover on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}/plannedFailover", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Planned operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Planned operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Planned 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _protectedItemName; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ProtectedItemName { get => this._protectedItemName; set => this._protectedItemName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString Clone() + { + var clone = new InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString(); + 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.VaultName = this.VaultName; + clone.ProtectedItemName = this.ProtectedItemName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 InvokeAzRecoveryServicesDataReplicationPlannedProtectedItemFailover_PlannedViaJsonString() + { + + } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemPlannedFailover' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemPlannedFailoverViaJsonString(SubscriptionId, ResourceGroupName, VaultName, ProtectedItemName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,ProtectedItemName=ProtectedItemName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + /// 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.RecoveryServicesDataReplication.Models.IPlannedFailoverModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateExpanded.cs new file mode 100644 index 00000000000..77793ea0621 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateExpanded.cs @@ -0,0 +1,614 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create an alert configuration setting for the given vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationEmailConfiguration_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create an alert configuration setting for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Email configuration model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Gets or sets the custom email address for sending emails. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the custom email address for sending emails.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the custom email address for sending emails.", + SerializedName = @"customEmailAddresses", + PossibleTypes = new [] { typeof(string) })] + public string[] CustomEmailAddress { get => _resourceBody.CustomEmailAddress?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.CustomEmailAddress = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; } } + + /// Gets or sets the locale for the email notification. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the locale for the email notification.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the locale for the email notification.", + SerializedName = @"locale", + PossibleTypes = new [] { typeof(string) })] + public string Locale { get => _resourceBody.Locale ?? null; set => _resourceBody.Locale = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets a value indicating whether to send email to subscription administrator.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets a value indicating whether to send email to subscription administrator.", + SerializedName = @"sendToOwners", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SendToOwner { get => _resourceBody.SendToOwner ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.SendToOwner = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'EmailConfigurationCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EmailConfigurationCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..c32fb595232 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonFilePath.cs @@ -0,0 +1,591 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create an alert configuration setting for the given vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create an alert configuration setting for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'EmailConfigurationCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EmailConfigurationCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonString.cs new file mode 100644 index 00000000000..f7839a83c15 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonString.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create an alert configuration setting for the given vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create an alert configuration setting for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationEmailConfiguration_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'EmailConfigurationCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.EmailConfigurationCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateExpanded.cs new file mode 100644 index 00000000000..62aa5325109 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateExpanded.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the replication extension in the given vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationExtension_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationExtension_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Replication extension model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ReplicationExtensionModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationExtension_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationExtension_CreateExpanded Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationExtension_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationExtension_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..d84916dd5dd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the replication extension in the given vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationExtension_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString.cs new file mode 100644 index 00000000000..3a3857e31e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the replication extension in the given vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationExtension_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationExtension_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationExtension_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded.cs new file mode 100644 index 00000000000..842db062031 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded.cs @@ -0,0 +1,742 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the fabric agent. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationFabricAgent_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric agent model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAadAuthority { get => _resourceBody.AuthenticationIdentityAadAuthority ?? null; set => _resourceBody.AuthenticationIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityApplicationId { get => _resourceBody.AuthenticationIdentityApplicationId ?? null; set => _resourceBody.AuthenticationIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAudience { get => _resourceBody.AuthenticationIdentityAudience ?? null; set => _resourceBody.AuthenticationIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityObjectId { get => _resourceBody.AuthenticationIdentityObjectId ?? null; set => _resourceBody.AuthenticationIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityTenantId { get => _resourceBody.AuthenticationIdentityTenantId ?? null; set => _resourceBody.AuthenticationIdentityTenantId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricAgentModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricAgentModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; } } + + /// Gets or sets the machine Id where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine Id where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine Id where fabric agent is running.", + SerializedName = @"machineId", + PossibleTypes = new [] { typeof(string) })] + public string MachineId { get => _resourceBody.MachineId ?? null; set => _resourceBody.MachineId = value; } + + /// Gets or sets the machine name where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine name where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine name where fabric agent is running.", + SerializedName = @"machineName", + PossibleTypes = new [] { typeof(string) })] + public string MachineName { get => _resourceBody.MachineName ?? null; set => _resourceBody.MachineName = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAadAuthority { get => _resourceBody.ResourceAccessIdentityAadAuthority ?? null; set => _resourceBody.ResourceAccessIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityApplicationId { get => _resourceBody.ResourceAccessIdentityApplicationId ?? null; set => _resourceBody.ResourceAccessIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAudience { get => _resourceBody.ResourceAccessIdentityAudience ?? null; set => _resourceBody.ResourceAccessIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityObjectId { get => _resourceBody.ResourceAccessIdentityObjectId ?? null; set => _resourceBody.ResourceAccessIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityTenantId { get => _resourceBody.ResourceAccessIdentityTenantId ?? null; set => _resourceBody.ResourceAccessIdentityTenantId = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationFabricAgent_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.FabricName = this.FabricName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationFabricAgent_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentCreate(SubscriptionId, ResourceGroupName, FabricName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..2ef74d62e56 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the fabric agent. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationFabricAgent_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.FabricName = this.FabricName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentCreateViaJsonString(SubscriptionId, ResourceGroupName, FabricName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString.cs new file mode 100644 index 00000000000..d256bd0a82d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the fabric agent. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationFabricAgent_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.FabricName = this.FabricName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationFabricAgent_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentCreateViaJsonString(SubscriptionId, ResourceGroupName, FabricName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateExpanded.cs new file mode 100644 index 00000000000..a5a2b0bb10d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateExpanded.cs @@ -0,0 +1,597 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the fabric. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationFabric_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationFabric_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationFabric_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationFabric_CreateExpanded Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationFabric_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricCreate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..4d424c3b199 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath.cs @@ -0,0 +1,577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the fabric. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricCreateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString.cs new file mode 100644 index 00000000000..da8b65de853 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString.cs @@ -0,0 +1,575 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the fabric. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationFabric_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationFabric_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricCreateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded.cs new file mode 100644 index 00000000000..0967b0a2b17 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded.cs @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the policy. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationPolicy_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Policy model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PolicyModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for PolicyModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationPolicy_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationPolicy_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..b7611e0a790 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the policy. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationPolicy_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString.cs new file mode 100644 index 00000000000..c8efd2120bc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the policy. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationPolicy_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationPolicy_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationPolicy_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateExpanded.cs new file mode 100644 index 00000000000..cc027b943aa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateExpanded.cs @@ -0,0 +1,657 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also create a private endpoint connection resource. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also create a private endpoint connection resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _resourceBody.Etag ?? null; set => _resourceBody.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _resourceBody.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _resourceBody.RemotePrivateEndpointId ?? null; set => _resourceBody.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..0509303991a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonFilePath.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also create a private endpoint connection resource. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also create a private endpoint connection resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonString.cs new file mode 100644 index 00000000000..66a00ed4f73 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonString.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also create a private endpoint connection resource. + /// + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also create a private endpoint connection resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded.cs new file mode 100644 index 00000000000..d2d22bc97ef --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded.cs @@ -0,0 +1,612 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the protected item. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationProtectedItem_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Protected item model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ProtectedItemModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ProtectedItemModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ProtectedItemModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.HttpPipeline Pipeline { get; set; } + + /// Gets or sets the policy name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the policy name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + public string PolicyName { get => _resourceBody.PolicyName ?? null; set => _resourceBody.PolicyName = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Gets or sets the replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the replication extension name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + public string ReplicationExtensionName { get => _resourceBody.ReplicationExtensionName ?? null; set => _resourceBody.ReplicationExtensionName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationProtectedItem_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationProtectedItem_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..925c7b030ab --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the protected item. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationProtectedItem_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString.cs new file mode 100644 index 00000000000..406f20e03dd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the protected item. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationProtectedItem_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationProtectedItem_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemCreateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateExpanded.cs new file mode 100644 index 00000000000..95f1cc6d7cc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateExpanded.cs @@ -0,0 +1,636 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationVault_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + public partial class NewAzRecoveryServicesDataReplicationVault_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Vault model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("VaultName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags 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; } + + /// Gets or sets the type of vault. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the type of vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the type of vault.", + SerializedName = @"vaultType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + public string VaultType { get => _resourceBody.VaultType ?? null; set => _resourceBody.VaultType = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationVault_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationVault_CreateExpanded Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationVault_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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.VaultCreate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..1be720b4676 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath.cs @@ -0,0 +1,577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("VaultName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationVault_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultCreateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString.cs new file mode 100644 index 00000000000..7994a4223a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString.cs @@ -0,0 +1,575 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// create the vault. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzRecoveryServicesDataReplicationVault_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"create the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("VaultName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString Clone() + { + var clone = new NewAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 NewAzRecoveryServicesDataReplicationVault_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultCreateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_Delete.cs new file mode 100644 index 00000000000..7439dcc2a84 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_Delete.cs @@ -0,0 +1,610 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Deletes the replication extension in the given vault. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationExtension_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Deletes the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationExtension_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationExtension_Delete + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationExtension_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationExtension_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ReplicationExtensionDelete(SubscriptionId, ResourceGroupName, VaultName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationExtension_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity.cs new file mode 100644 index 00000000000..617bb338bdd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity.cs @@ -0,0 +1,579 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Deletes the replication extension in the given vault. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationExtension_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Deletes the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationExtension_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ReplicationExtensionDeleteViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ReplicationExtensionName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ReplicationExtensionName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ReplicationExtensionDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ReplicationExtensionName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..44e43fbbf8f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Deletes the replication extension in the given vault. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Deletes the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/replicationExtensions/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ReplicationExtensionDeleteViaIdentity(ReplicationVaultInputObject.Id, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ReplicationExtensionDelete(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationExtension_DeleteViaIdentityReplicationVault() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete.cs new file mode 100644 index 00000000000..49615b19de0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete.cs @@ -0,0 +1,612 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Deletes fabric agent. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationFabricAgent_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Deletes fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationFabricAgent_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.FabricName = this.FabricName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricAgentDelete(SubscriptionId, ResourceGroupName, FabricName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationFabricAgent_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity.cs new file mode 100644 index 00000000000..0b914d0b196 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity.cs @@ -0,0 +1,579 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Deletes fabric agent. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Deletes fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationFabricAgent_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FabricAgentDeleteViaIdentity(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.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FabricAgentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricAgentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FabricAgentDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, InputObject.FabricAgentName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric.cs new file mode 100644 index 00000000000..c8ff8f04f4d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Deletes fabric agent. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Deletes fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationFabricInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationFabricInputObject { get => this._replicationFabricInputObject; set => this._replicationFabricInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationFabricInputObject?.Id != null) + { + this.ReplicationFabricInputObject.Id += $"/fabricAgents/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.FabricAgentDeleteViaIdentity(ReplicationFabricInputObject.Id, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationFabricInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + if (null == ReplicationFabricInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + if (null == ReplicationFabricInputObject.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + await this.Client.FabricAgentDelete(ReplicationFabricInputObject.SubscriptionId ?? null, ReplicationFabricInputObject.ResourceGroupName ?? null, ReplicationFabricInputObject.FabricName ?? null, Name, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationFabricAgent_DeleteViaIdentityReplicationFabric() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabric_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabric_Delete.cs new file mode 100644 index 00000000000..3b1b4b118f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabric_Delete.cs @@ -0,0 +1,595 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the fabric. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationFabric_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationFabric_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationFabric_Delete + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationFabric_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricDelete(SubscriptionId, ResourceGroupName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationFabric_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity.cs new file mode 100644 index 00000000000..09349693faa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity.cs @@ -0,0 +1,575 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the fabric. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationFabric_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FabricDeleteViaIdentity(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.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FabricDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzRecoveryServicesDataReplicationFabric_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_Delete.cs new file mode 100644 index 00000000000..9e84c0df19d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_Delete.cs @@ -0,0 +1,610 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the policy. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationPolicy_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationPolicy_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationPolicy_Delete + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationPolicy_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationPolicy_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PolicyDelete(SubscriptionId, ResourceGroupName, VaultName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationPolicy_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity.cs new file mode 100644 index 00000000000..c32b02e4abc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity.cs @@ -0,0 +1,579 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the policy. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationPolicy_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PolicyDeleteViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PolicyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PolicyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PolicyDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PolicyName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..0b7c0cb5ed4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the policy. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/replicationPolicies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.PolicyDeleteViaIdentity(ReplicationVaultInputObject.Id, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.PolicyDelete(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationPolicy_DeleteViaIdentityReplicationVault() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete.cs new file mode 100644 index 00000000000..2ae018202dc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// Returns the operation to track the deletion of private endpoint connection proxy. + /// + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns the operation to track the deletion of private endpoint connection proxy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesDelete(SubscriptionId, ResourceGroupName, VaultName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity.cs new file mode 100644 index 00000000000..4a445711d57 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity.cs @@ -0,0 +1,581 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// Returns the operation to track the deletion of private endpoint connection proxy. + /// + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns the operation to track the deletion of private endpoint connection proxy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PrivateEndpointConnectionProxiesDeleteViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PrivateEndpointConnectionProxyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PrivateEndpointConnectionProxyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PrivateEndpointConnectionProxyName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..e64f694dde4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// Returns the operation to track the deletion of private endpoint connection proxy. + /// + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns the operation to track the deletion of private endpoint connection proxy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/privateEndpointConnectionProxies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.PrivateEndpointConnectionProxiesDeleteViaIdentity(ReplicationVaultInputObject.Id, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesDelete(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_DeleteViaIdentityReplicationVault() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete.cs new file mode 100644 index 00000000000..92c242db01b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete.cs @@ -0,0 +1,627 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the protected item. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationProtectedItem_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private global::System.Management.Automation.SwitchParameter _forceDelete; + + /// A flag indicating whether to do force delete or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A flag indicating whether to do force delete or not.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A flag indicating whether to do force delete or not.", + SerializedName = @"forceDelete", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public global::System.Management.Automation.SwitchParameter ForceDelete { get => this._forceDelete; set => this._forceDelete = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationProtectedItem_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.ForceDelete = this.ForceDelete; + clone.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemDelete(SubscriptionId, ResourceGroupName, VaultName, Name, this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?), onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,ForceDelete=this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?),VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationProtectedItem_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity.cs new file mode 100644 index 00000000000..3918089d720 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the protected item. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private global::System.Management.Automation.SwitchParameter _forceDelete; + + /// A flag indicating whether to do force delete or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A flag indicating whether to do force delete or not.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A flag indicating whether to do force delete or not.", + SerializedName = @"forceDelete", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public global::System.Management.Automation.SwitchParameter ForceDelete { get => this._forceDelete; set => this._forceDelete = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationProtectedItem_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; + clone.ForceDelete = this.ForceDelete; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProtectedItemDeleteViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?), 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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProtectedItemDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ProtectedItemName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?), onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ForceDelete=this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?)}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..558f968aca1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault.cs @@ -0,0 +1,607 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the protected item. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private global::System.Management.Automation.SwitchParameter _forceDelete; + + /// A flag indicating whether to do force delete or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A flag indicating whether to do force delete or not.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A flag indicating whether to do force delete or not.", + SerializedName = @"forceDelete", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Query)] + public global::System.Management.Automation.SwitchParameter ForceDelete { get => this._forceDelete; set => this._forceDelete = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault(); + 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.ForceDelete = this.ForceDelete; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/protectedItems/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ProtectedItemDeleteViaIdentity(ReplicationVaultInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?), onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ProtectedItemDelete(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?), onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ForceDelete=this.InvocationInformation.BoundParameters.ContainsKey("ForceDelete") ? ForceDelete : default(global::System.Management.Automation.SwitchParameter?),Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationProtectedItem_DeleteViaIdentityReplicationVault() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationVault_Delete.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationVault_Delete.cs new file mode 100644 index 00000000000..6e4e8861da4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationVault_Delete.cs @@ -0,0 +1,595 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the vault. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationVault_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationVault_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("VaultName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationVault_Delete + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationVault_Delete Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultDelete(SubscriptionId, ResourceGroupName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzRecoveryServicesDataReplicationVault_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity.cs new file mode 100644 index 00000000000..51b120922bb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity.cs @@ -0,0 +1,575 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Removes the vault. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzRecoveryServicesDataReplicationVault_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Removes the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}", ApiVersion = "2024-09-01")] + public partial class RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity Clone() + { + var clone = new RemoveAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.VaultDeleteViaIdentity(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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.VaultDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzRecoveryServicesDataReplicationVault_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Validate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Validate.cs new file mode 100644 index 00000000000..529371fded3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Validate.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Validate", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Validate : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _body; + + /// Represents private endpoint connection proxy request. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Represents private endpoint connection proxy request.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Represents private endpoint connection proxy request.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesValidate(SubscriptionId, ResourceGroupName, VaultName, Name, Body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_Validate() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateExpanded.cs new file mode 100644 index 00000000000..d639807a507 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateExpanded.cs @@ -0,0 +1,600 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _body.Etag ?? null; set => _body.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _body.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _body.RemotePrivateEndpointId ?? null; set => _body.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _body.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _body.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _body.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesValidate(SubscriptionId, ResourceGroupName, VaultName, Name, _body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentity.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentity.cs new file mode 100644 index 00000000000..65b8e3a7219 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentity.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _body; + + /// Represents private endpoint connection proxy request. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Represents private endpoint connection proxy request.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Represents private endpoint connection proxy request.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PrivateEndpointConnectionProxiesValidateViaIdentity(InputObject.Id, Body, 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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PrivateEndpointConnectionProxyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PrivateEndpointConnectionProxyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesValidate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PrivateEndpointConnectionProxyName ?? null, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentity() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityExpanded.cs new file mode 100644 index 00000000000..ce40e265198 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityExpanded.cs @@ -0,0 +1,570 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _body.Etag ?? null; set => _body.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _body.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _body.RemotePrivateEndpointId ?? null; set => _body.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _body.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _body.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _body.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PrivateEndpointConnectionProxiesValidateViaIdentity(InputObject.Id, _body, 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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PrivateEndpointConnectionProxyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PrivateEndpointConnectionProxyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesValidate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PrivateEndpointConnectionProxyName ?? null, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVault.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVault.cs new file mode 100644 index 00000000000..5c016c86b3a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVault.cs @@ -0,0 +1,517 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVault", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVault : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _body; + + /// Represents private endpoint connection proxy request. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Represents private endpoint connection proxy request.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Represents private endpoint connection proxy request.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/privateEndpointConnectionProxies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.PrivateEndpointConnectionProxiesValidateViaIdentity(ReplicationVaultInputObject.Id, Body, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesValidate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVault() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..9e11660a5e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVaultExpanded.cs @@ -0,0 +1,582 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _body = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _body.Etag ?? null; set => _body.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _body.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _body.RemotePrivateEndpointId ?? null; set => _body.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _body.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _body.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _body.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _body.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/privateEndpointConnectionProxies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.PrivateEndpointConnectionProxiesValidateViaIdentity(ReplicationVaultInputObject.Id, _body, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.PrivateEndpointConnectionProxiesValidate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaIdentityReplicationVaultExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonFilePath.cs new file mode 100644 index 00000000000..b84b3547081 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonFilePath.cs @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Validate operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Validate operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Validate 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesValidateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonString.cs new file mode 100644 index 00000000000..40738f334b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Returns remote private endpoint connection information after validation. + /// + /// [OpenAPI] Validate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Returns remote private endpoint connection information after validation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}/validate", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 Validate operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Validate operation")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Validate 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesValidate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PrivateEndpointConnectionProxiesValidateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_ValidateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateExpanded.cs new file mode 100644 index 00000000000..7783eab6186 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateExpanded.cs @@ -0,0 +1,632 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update an alert configuration setting for the given vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationEmailConfiguration_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update an alert configuration setting for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Email configuration model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Gets or sets the custom email address for sending emails. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the custom email address for sending emails.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the custom email address for sending emails.", + SerializedName = @"customEmailAddresses", + PossibleTypes = new [] { typeof(string) })] + public string[] CustomEmailAddress { get => _resourceBody.CustomEmailAddress?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.CustomEmailAddress = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; } } + + /// Gets or sets the locale for the email notification. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the locale for the email notification.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the locale for the email notification.", + SerializedName = @"locale", + PossibleTypes = new [] { typeof(string) })] + public string Locale { get => _resourceBody.Locale ?? null; set => _resourceBody.Locale = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets a value indicating whether to send email to subscription administrator.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets a value indicating whether to send email to subscription administrator.", + SerializedName = @"sendToOwners", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SendToOwner { get => _resourceBody.SendToOwner ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.SendToOwner = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'EmailConfigurationCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.EmailConfigurationGetWithResult(SubscriptionId, ResourceGroupName, VaultName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.EmailConfigurationCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SendToOwner"))) + { + this.SendToOwner = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SendToOwner"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomEmailAddress"))) + { + this.CustomEmailAddress = (string[])(this.MyInvocation?.BoundParameters["CustomEmailAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Locale"))) + { + this.Locale = (string)(this.MyInvocation?.BoundParameters["Locale"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..bcbbf45d635 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityExpanded.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update an alert configuration setting for the given vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update an alert configuration setting for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Email configuration model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Gets or sets the custom email address for sending emails. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the custom email address for sending emails.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the custom email address for sending emails.", + SerializedName = @"customEmailAddresses", + PossibleTypes = new [] { typeof(string) })] + public string[] CustomEmailAddress { get => _resourceBody.CustomEmailAddress?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.CustomEmailAddress = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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; } } + + /// Gets or sets the locale for the email notification. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the locale for the email notification.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the locale for the email notification.", + SerializedName = @"locale", + PossibleTypes = new [] { typeof(string) })] + public string Locale { get => _resourceBody.Locale ?? null; set => _resourceBody.Locale = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets a value indicating whether to send email to subscription administrator.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets a value indicating whether to send email to subscription administrator.", + SerializedName = @"sendToOwners", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SendToOwner { get => _resourceBody.SendToOwner ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.SendToOwner = 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'EmailConfigurationCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.EmailConfigurationGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.EmailConfigurationCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.EmailConfigurationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.EmailConfigurationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.EmailConfigurationGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.EmailConfigurationName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.EmailConfigurationCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.EmailConfigurationName ?? null, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SendToOwner"))) + { + this.SendToOwner = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SendToOwner"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomEmailAddress"))) + { + this.CustomEmailAddress = (string[])(this.MyInvocation?.BoundParameters["CustomEmailAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Locale"))) + { + this.Locale = (string)(this.MyInvocation?.BoundParameters["Locale"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..a57a0ac35d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityReplicationVaultExpanded.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update an alert configuration setting for the given vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/alertSettings/{emailConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update an alert configuration setting for the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Email configuration model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IEmailConfigurationModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.EmailConfigurationModel(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Gets or sets the custom email address for sending emails. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the custom email address for sending emails.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the custom email address for sending emails.", + SerializedName = @"customEmailAddresses", + PossibleTypes = new [] { typeof(string) })] + public string[] CustomEmailAddress { get => _resourceBody.CustomEmailAddress?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.CustomEmailAddress = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; } } + + /// Gets or sets the locale for the email notification. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the locale for the email notification.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the locale for the email notification.", + SerializedName = @"locale", + PossibleTypes = new [] { typeof(string) })] + public string Locale { get => _resourceBody.Locale ?? null; set => _resourceBody.Locale = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The email configuration name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The email configuration name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The email configuration name.", + SerializedName = @"emailConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("EmailConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = value; } + + /// + /// Gets or sets a value indicating whether to send email to subscription administrator. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets a value indicating whether to send email to subscription administrator.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets a value indicating whether to send email to subscription administrator.", + SerializedName = @"sendToOwners", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter SendToOwner { get => _resourceBody.SendToOwner ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.SendToOwner = 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'EmailConfigurationCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/alertSettings/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.EmailConfigurationGetViaIdentityWithResult(ReplicationVaultInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.EmailConfigurationCreateViaIdentity(ReplicationVaultInputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + _resourceBody = await this.Client.EmailConfigurationGetWithResult(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.EmailConfigurationCreate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationEmailConfiguration_UpdateViaIdentityReplicationVaultExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SendToOwner"))) + { + this.SendToOwner = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["SendToOwner"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomEmailAddress"))) + { + this.CustomEmailAddress = (string[])(this.MyInvocation?.BoundParameters["CustomEmailAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Locale"))) + { + this.Locale = (string)(this.MyInvocation?.BoundParameters["Locale"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + /// 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.RecoveryServicesDataReplication.Models.IEmailConfigurationModel + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded.cs new file mode 100644 index 00000000000..9a2885bfb12 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded.cs @@ -0,0 +1,600 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the replication extension in the given vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationExtension_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Replication extension model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ReplicationExtensionModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationExtension_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.ReplicationExtensionGetWithResult(SubscriptionId, ResourceGroupName, VaultName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.ReplicationExtensionCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzRecoveryServicesDataReplicationExtension_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..dfe1a67030d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the replication extension in the given vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Replication extension model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ReplicationExtensionModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationExtension_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.ReplicationExtensionGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.ReplicationExtensionCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ReplicationExtensionName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ReplicationExtensionName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.ReplicationExtensionGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ReplicationExtensionName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.ReplicationExtensionCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ReplicationExtensionName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..01f34aa97c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded.cs @@ -0,0 +1,581 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the replication extension in the given vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationExtensions/{replicationExtensionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the replication extension in the given vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Replication extension model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IReplicationExtensionModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ReplicationExtensionModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ReplicationExtensionModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ReplicationExtensionModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ReplicationExtensionModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The replication extension name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The replication extension name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The replication extension name.", + SerializedName = @"replicationExtensionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ReplicationExtensionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ReplicationExtensionCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/replicationExtensions/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.ReplicationExtensionGetViaIdentityWithResult(ReplicationVaultInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.ReplicationExtensionCreateViaIdentity(ReplicationVaultInputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + _resourceBody = await this.Client.ReplicationExtensionGetWithResult(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.ReplicationExtensionCreate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationExtension_UpdateViaIdentityReplicationVaultExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + /// 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.RecoveryServicesDataReplication.Models.IReplicationExtensionModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded.cs new file mode 100644 index 00000000000..9ed07f25722 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded.cs @@ -0,0 +1,800 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the fabric agent. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric agent model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAadAuthority { get => _resourceBody.AuthenticationIdentityAadAuthority ?? null; set => _resourceBody.AuthenticationIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityApplicationId { get => _resourceBody.AuthenticationIdentityApplicationId ?? null; set => _resourceBody.AuthenticationIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAudience { get => _resourceBody.AuthenticationIdentityAudience ?? null; set => _resourceBody.AuthenticationIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityObjectId { get => _resourceBody.AuthenticationIdentityObjectId ?? null; set => _resourceBody.AuthenticationIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityTenantId { get => _resourceBody.AuthenticationIdentityTenantId ?? null; set => _resourceBody.AuthenticationIdentityTenantId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricAgentModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricAgentModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fabricName; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string FabricName { get => this._fabricName; set => this._fabricName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; } } + + /// Gets or sets the machine Id where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine Id where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine Id where fabric agent is running.", + SerializedName = @"machineId", + PossibleTypes = new [] { typeof(string) })] + public string MachineId { get => _resourceBody.MachineId ?? null; set => _resourceBody.MachineId = value; } + + /// Gets or sets the machine name where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine name where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine name where fabric agent is running.", + SerializedName = @"machineName", + PossibleTypes = new [] { typeof(string) })] + public string MachineName { get => _resourceBody.MachineName ?? null; set => _resourceBody.MachineName = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAadAuthority { get => _resourceBody.ResourceAccessIdentityAadAuthority ?? null; set => _resourceBody.ResourceAccessIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityApplicationId { get => _resourceBody.ResourceAccessIdentityApplicationId ?? null; set => _resourceBody.ResourceAccessIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAudience { get => _resourceBody.ResourceAccessIdentityAudience ?? null; set => _resourceBody.ResourceAccessIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityObjectId { get => _resourceBody.ResourceAccessIdentityObjectId ?? null; set => _resourceBody.ResourceAccessIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityTenantId { get => _resourceBody.ResourceAccessIdentityTenantId ?? null; set => _resourceBody.ResourceAccessIdentityTenantId = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabricAgent_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.FabricName = this.FabricName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.FabricAgentGetWithResult(SubscriptionId, ResourceGroupName, FabricName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FabricAgentCreate(SubscriptionId, ResourceGroupName, FabricName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,FabricName=FabricName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MachineId"))) + { + this.MachineId = (string)(this.MyInvocation?.BoundParameters["MachineId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MachineName"))) + { + this.MachineName = (string)(this.MyInvocation?.BoundParameters["MachineName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityTenantId"))) + { + this.AuthenticationIdentityTenantId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityTenantId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityApplicationId"))) + { + this.AuthenticationIdentityApplicationId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityApplicationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityObjectId"))) + { + this.AuthenticationIdentityObjectId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityObjectId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityAudience"))) + { + this.AuthenticationIdentityAudience = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityAudience"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityAadAuthority"))) + { + this.AuthenticationIdentityAadAuthority = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityAadAuthority"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityTenantId"))) + { + this.ResourceAccessIdentityTenantId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityTenantId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityApplicationId"))) + { + this.ResourceAccessIdentityApplicationId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityApplicationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityObjectId"))) + { + this.ResourceAccessIdentityObjectId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityObjectId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityAudience"))) + { + this.ResourceAccessIdentityAudience = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityAudience"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityAadAuthority"))) + { + this.ResourceAccessIdentityAadAuthority = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityAadAuthority"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..2d2b3f1ee5b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded.cs @@ -0,0 +1,768 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the fabric agent. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric agent model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAadAuthority { get => _resourceBody.AuthenticationIdentityAadAuthority ?? null; set => _resourceBody.AuthenticationIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityApplicationId { get => _resourceBody.AuthenticationIdentityApplicationId ?? null; set => _resourceBody.AuthenticationIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAudience { get => _resourceBody.AuthenticationIdentityAudience ?? null; set => _resourceBody.AuthenticationIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityObjectId { get => _resourceBody.AuthenticationIdentityObjectId ?? null; set => _resourceBody.AuthenticationIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityTenantId { get => _resourceBody.AuthenticationIdentityTenantId ?? null; set => _resourceBody.AuthenticationIdentityTenantId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricAgentModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricAgentModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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; } } + + /// Gets or sets the machine Id where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine Id where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine Id where fabric agent is running.", + SerializedName = @"machineId", + PossibleTypes = new [] { typeof(string) })] + public string MachineId { get => _resourceBody.MachineId ?? null; set => _resourceBody.MachineId = value; } + + /// Gets or sets the machine name where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine name where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine name where fabric agent is running.", + SerializedName = @"machineName", + PossibleTypes = new [] { typeof(string) })] + public string MachineName { get => _resourceBody.MachineName ?? null; set => _resourceBody.MachineName = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAadAuthority { get => _resourceBody.ResourceAccessIdentityAadAuthority ?? null; set => _resourceBody.ResourceAccessIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityApplicationId { get => _resourceBody.ResourceAccessIdentityApplicationId ?? null; set => _resourceBody.ResourceAccessIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAudience { get => _resourceBody.ResourceAccessIdentityAudience ?? null; set => _resourceBody.ResourceAccessIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityObjectId { get => _resourceBody.ResourceAccessIdentityObjectId ?? null; set => _resourceBody.ResourceAccessIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityTenantId { get => _resourceBody.ResourceAccessIdentityTenantId ?? null; set => _resourceBody.ResourceAccessIdentityTenantId = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabricAgent_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.FabricAgentGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FabricAgentCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FabricAgentName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricAgentName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.FabricAgentGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, InputObject.FabricAgentName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FabricAgentCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, InputObject.FabricAgentName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MachineId"))) + { + this.MachineId = (string)(this.MyInvocation?.BoundParameters["MachineId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MachineName"))) + { + this.MachineName = (string)(this.MyInvocation?.BoundParameters["MachineName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityTenantId"))) + { + this.AuthenticationIdentityTenantId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityTenantId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityApplicationId"))) + { + this.AuthenticationIdentityApplicationId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityApplicationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityObjectId"))) + { + this.AuthenticationIdentityObjectId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityObjectId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityAudience"))) + { + this.AuthenticationIdentityAudience = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityAudience"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityAadAuthority"))) + { + this.AuthenticationIdentityAadAuthority = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityAadAuthority"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityTenantId"))) + { + this.ResourceAccessIdentityTenantId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityTenantId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityApplicationId"))) + { + this.ResourceAccessIdentityApplicationId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityApplicationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityObjectId"))) + { + this.ResourceAccessIdentityObjectId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityObjectId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityAudience"))) + { + this.ResourceAccessIdentityAudience = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityAudience"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityAadAuthority"))) + { + this.ResourceAccessIdentityAadAuthority = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityAadAuthority"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded.cs new file mode 100644 index 00000000000..3bac98835a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded.cs @@ -0,0 +1,781 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the fabric agent. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}/fabricAgents/{fabricAgentName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the fabric agent.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric agent model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricAgentModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricAgentModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAadAuthority { get => _resourceBody.AuthenticationIdentityAadAuthority ?? null; set => _resourceBody.AuthenticationIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityApplicationId { get => _resourceBody.AuthenticationIdentityApplicationId ?? null; set => _resourceBody.AuthenticationIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityAudience { get => _resourceBody.AuthenticationIdentityAudience ?? null; set => _resourceBody.AuthenticationIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityObjectId { get => _resourceBody.AuthenticationIdentityObjectId ?? null; set => _resourceBody.AuthenticationIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string AuthenticationIdentityTenantId { get => _resourceBody.AuthenticationIdentityTenantId ?? null; set => _resourceBody.AuthenticationIdentityTenantId = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricAgentModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricAgentModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricAgentModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; } } + + /// Gets or sets the machine Id where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine Id where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine Id where fabric agent is running.", + SerializedName = @"machineId", + PossibleTypes = new [] { typeof(string) })] + public string MachineId { get => _resourceBody.MachineId ?? null; set => _resourceBody.MachineId = value; } + + /// Gets or sets the machine name where fabric agent is running. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the machine name where fabric agent is running.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the machine name where fabric agent is running.", + SerializedName = @"machineName", + PossibleTypes = new [] { typeof(string) })] + public string MachineName { get => _resourceBody.MachineName ?? null; set => _resourceBody.MachineName = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric agent name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric agent name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric agent name.", + SerializedName = @"fabricAgentName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricAgentName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationFabricInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationFabricInputObject { get => this._replicationFabricInputObject; set => this._replicationFabricInputObject = value; } + + /// + /// Gets or sets the authority of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the authority of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the authority of the SPN with which fabric agent communicates to service.", + SerializedName = @"aadAuthority", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAadAuthority { get => _resourceBody.ResourceAccessIdentityAadAuthority ?? null; set => _resourceBody.ResourceAccessIdentityAadAuthority = value; } + + /// + /// Gets or sets the client/application Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the client/application Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityApplicationId { get => _resourceBody.ResourceAccessIdentityApplicationId ?? null; set => _resourceBody.ResourceAccessIdentityApplicationId = value; } + + /// + /// Gets or sets the audience of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the audience of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the audience of the SPN with which fabric agent communicates to service.", + SerializedName = @"audience", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityAudience { get => _resourceBody.ResourceAccessIdentityAudience ?? null; set => _resourceBody.ResourceAccessIdentityAudience = value; } + + /// + /// Gets or sets the object Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the object Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the object Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityObjectId { get => _resourceBody.ResourceAccessIdentityObjectId ?? null; set => _resourceBody.ResourceAccessIdentityObjectId = value; } + + /// + /// Gets or sets the tenant Id of the SPN with which fabric agent communicates to service. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the tenant Id of the SPN with which fabric agent communicates to service.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string ResourceAccessIdentityTenantId { get => _resourceBody.ResourceAccessIdentityTenantId ?? null; set => _resourceBody.ResourceAccessIdentityTenantId = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricAgentCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationFabricInputObject?.Id != null) + { + this.ReplicationFabricInputObject.Id += $"/fabricAgents/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.FabricAgentGetViaIdentityWithResult(ReplicationFabricInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FabricAgentCreateViaIdentity(ReplicationFabricInputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationFabricInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + if (null == ReplicationFabricInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + if (null == ReplicationFabricInputObject.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationFabricInputObject has null value for ReplicationFabricInputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationFabricInputObject) ); + } + _resourceBody = await this.Client.FabricAgentGetWithResult(ReplicationFabricInputObject.SubscriptionId ?? null, ReplicationFabricInputObject.ResourceGroupName ?? null, ReplicationFabricInputObject.FabricName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FabricAgentCreate(ReplicationFabricInputObject.SubscriptionId ?? null, ReplicationFabricInputObject.ResourceGroupName ?? null, ReplicationFabricInputObject.FabricName ?? null, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationFabricAgent_UpdateViaIdentityReplicationFabricExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MachineId"))) + { + this.MachineId = (string)(this.MyInvocation?.BoundParameters["MachineId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MachineName"))) + { + this.MachineName = (string)(this.MyInvocation?.BoundParameters["MachineName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityTenantId"))) + { + this.AuthenticationIdentityTenantId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityTenantId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityApplicationId"))) + { + this.AuthenticationIdentityApplicationId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityApplicationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityObjectId"))) + { + this.AuthenticationIdentityObjectId = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityObjectId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityAudience"))) + { + this.AuthenticationIdentityAudience = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityAudience"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AuthenticationIdentityAadAuthority"))) + { + this.AuthenticationIdentityAadAuthority = (string)(this.MyInvocation?.BoundParameters["AuthenticationIdentityAadAuthority"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityTenantId"))) + { + this.ResourceAccessIdentityTenantId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityTenantId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityApplicationId"))) + { + this.ResourceAccessIdentityApplicationId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityApplicationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityObjectId"))) + { + this.ResourceAccessIdentityObjectId = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityObjectId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityAudience"))) + { + this.ResourceAccessIdentityAudience = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityAudience"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ResourceAccessIdentityAadAuthority"))) + { + this.ResourceAccessIdentityAadAuthority = (string)(this.MyInvocation?.BoundParameters["ResourceAccessIdentityAadAuthority"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricAgentModel + /// 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.RecoveryServicesDataReplication.Models.IFabricAgentModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded.cs new file mode 100644 index 00000000000..87dd9228145 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the fabric. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabric_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric model update. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelUpdate(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _propertiesBody.CustomPropertyInstanceType ?? null; set => _propertiesBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Gets or sets the resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricUpdate(SubscriptionId, ResourceGroupName, Name, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationFabric_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..1527775d328 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded.cs @@ -0,0 +1,564 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the fabric. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + public partial class UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Fabric model update. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.FabricModelUpdate(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for FabricModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for FabricModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for FabricModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _propertiesBody.CustomPropertyInstanceType ?? null; set => _propertiesBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Gets or sets the resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModelUpdateTags 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FabricUpdateViaIdentity(InputObject.Id, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.FabricName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FabricName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FabricUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FabricName ?? null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..a7cf04fa5e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath.cs @@ -0,0 +1,577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the fabric. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString.cs new file mode 100644 index 00000000000..2cc0af27e02 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString.cs @@ -0,0 +1,575 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the fabric. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationFabric_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IFabricModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the fabric.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationFabrics/{fabricName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The fabric name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The fabric name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The fabric name.", + SerializedName = @"fabricName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FabricName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationFabric_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FabricUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FabricUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzRecoveryServicesDataReplicationFabric_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IFabricModel + /// 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.RecoveryServicesDataReplication.Models.IFabricModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded.cs new file mode 100644 index 00000000000..10ad399738e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded.cs @@ -0,0 +1,599 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the policy. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationPolicy_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Policy model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PolicyModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for PolicyModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationPolicy_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.PolicyGetWithResult(SubscriptionId, ResourceGroupName, VaultName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PolicyCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationPolicy_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..945c3980454 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the policy. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Policy model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PolicyModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for PolicyModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationPolicy_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.PolicyGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PolicyCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PolicyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PolicyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.PolicyGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PolicyName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PolicyCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PolicyName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..d2a2e38550d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded.cs @@ -0,0 +1,581 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the policy. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/replicationPolicies/{policyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the policy.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Policy model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPolicyModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PolicyModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for PolicyModelCustomProperties. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for PolicyModelCustomProperties.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for PolicyModelCustomProperties.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _resourceBody.CustomPropertyInstanceType ?? null; set => _resourceBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The policy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The policy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The policy name.", + SerializedName = @"policyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PolicyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PolicyCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/replicationPolicies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.PolicyGetViaIdentityWithResult(ReplicationVaultInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PolicyCreateViaIdentity(ReplicationVaultInputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + _resourceBody = await this.Client.PolicyGetWithResult(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PolicyCreate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationPolicy_UpdateViaIdentityReplicationVaultExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("CustomPropertyInstanceType"))) + { + this.CustomPropertyInstanceType = (string)(this.MyInvocation?.BoundParameters["CustomPropertyInstanceType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPolicyModel + /// 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.RecoveryServicesDataReplication.Models.IPolicyModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateExpanded.cs new file mode 100644 index 00000000000..cbf745dde39 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateExpanded.cs @@ -0,0 +1,687 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also update a private endpoint connection resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _resourceBody.Etag ?? null; set => _resourceBody.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _resourceBody.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _resourceBody.RemotePrivateEndpointId ?? null; set => _resourceBody.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// overrideOnCreated will be called before the regular onCreated has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.PrivateEndpointConnectionProxiesGetWithResult(SubscriptionId, ResourceGroupName, VaultName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PrivateEndpointConnectionProxiesCreate(SubscriptionId, ResourceGroupName, VaultName, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Etag"))) + { + this.Etag = (string)(this.MyInvocation?.BoundParameters["Etag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointConnectionDetail"))) + { + this.RemotePrivateEndpointConnectionDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointConnectionDetail"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointId"))) + { + this.RemotePrivateEndpointId = (string)(this.MyInvocation?.BoundParameters["RemotePrivateEndpointId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointPrivateLinkServiceConnection"))) + { + this.RemotePrivateEndpointPrivateLinkServiceConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointPrivateLinkServiceConnection"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointManualPrivateLinkServiceConnection"))) + { + this.RemotePrivateEndpointManualPrivateLinkServiceConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointManualPrivateLinkServiceConnection"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointPrivateLinkServiceProxy"))) + { + this.RemotePrivateEndpointPrivateLinkServiceProxy = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointPrivateLinkServiceProxy"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..df3fe2b298b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityExpanded.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also update a private endpoint connection resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _resourceBody.Etag ?? null; set => _resourceBody.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _resourceBody.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _resourceBody.RemotePrivateEndpointId ?? null; set => _resourceBody.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.PrivateEndpointConnectionProxiesGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PrivateEndpointConnectionProxiesCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.PrivateEndpointConnectionProxyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.PrivateEndpointConnectionProxyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.PrivateEndpointConnectionProxiesGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PrivateEndpointConnectionProxyName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PrivateEndpointConnectionProxiesCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.PrivateEndpointConnectionProxyName ?? null, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Etag"))) + { + this.Etag = (string)(this.MyInvocation?.BoundParameters["Etag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointConnectionDetail"))) + { + this.RemotePrivateEndpointConnectionDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointConnectionDetail"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointId"))) + { + this.RemotePrivateEndpointId = (string)(this.MyInvocation?.BoundParameters["RemotePrivateEndpointId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointPrivateLinkServiceConnection"))) + { + this.RemotePrivateEndpointPrivateLinkServiceConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointPrivateLinkServiceConnection"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointManualPrivateLinkServiceConnection"))) + { + this.RemotePrivateEndpointManualPrivateLinkServiceConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointManualPrivateLinkServiceConnection"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointPrivateLinkServiceProxy"))) + { + this.RemotePrivateEndpointPrivateLinkServiceProxy = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointPrivateLinkServiceProxy"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..9e93f091fa0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityReplicationVaultExpanded.cs @@ -0,0 +1,671 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// + /// update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy + /// resource will also update a private endpoint connection resource. + /// + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/privateEndpointConnectionProxies/{privateEndpointConnectionProxyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update a new private endpoint connection proxy which includes both auto and manual approval types. Creating the proxy resource will also update a private endpoint connection resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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; + + /// Represents private endpoint connection proxy request. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.PrivateEndpointConnectionProxy(); + + /// + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Gets or sets ETag. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets ETag.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets ETag.", + SerializedName = @"etag", + PossibleTypes = new [] { typeof(string) })] + public string Etag { get => _resourceBody.Etag ?? null; set => _resourceBody.Etag = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The private endpoint connection proxy name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The private endpoint connection proxy name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The private endpoint connection proxy name.", + SerializedName = @"privateEndpointConnectionProxyName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("PrivateEndpointConnectionProxyName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// Gets or sets the list of Connection Details. This is the connection details for private endpoint. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Connection Details. This is the connection details for private endpoint.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Connection Details. This is the connection details for private endpoint.", + SerializedName = @"connectionDetails", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[] RemotePrivateEndpointConnectionDetail { get => _resourceBody.RemotePrivateEndpointConnectionDetail?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointConnectionDetail = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets private link service proxy id. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets private link service proxy id.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets private link service proxy id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string RemotePrivateEndpointId { get => _resourceBody.RemotePrivateEndpointId ?? null; set => _resourceBody.RemotePrivateEndpointId = value; } + + /// + /// Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Manual Private Link Service Connections and gets populated for Manual approval flow.", + SerializedName = @"manualPrivateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointManualPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointManualPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of Private Link Service Connections and gets populated for Auto approval flow.", + SerializedName = @"privateLinkServiceConnections", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[] RemotePrivateEndpointPrivateLinkServiceConnection { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceConnection = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Gets or sets the list of private link service proxies. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the list of private link service proxies.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the list of private link service proxies.", + SerializedName = @"privateLinkServiceProxies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[] RemotePrivateEndpointPrivateLinkServiceProxy { get => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.RemotePrivateEndpointPrivateLinkServiceProxy = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PrivateEndpointConnectionProxiesCreate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/privateEndpointConnectionProxies/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.PrivateEndpointConnectionProxiesGetViaIdentityWithResult(ReplicationVaultInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PrivateEndpointConnectionProxiesCreateViaIdentity(ReplicationVaultInputObject.Id, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + _resourceBody = await this.Client.PrivateEndpointConnectionProxiesGetWithResult(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.PrivateEndpointConnectionProxiesCreate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, _resourceBody, onOk, onCreated, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationPrivateEndpointConnectionProxy_UpdateViaIdentityReplicationVaultExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Etag"))) + { + this.Etag = (string)(this.MyInvocation?.BoundParameters["Etag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointConnectionDetail"))) + { + this.RemotePrivateEndpointConnectionDetail = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IConnectionDetails[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointConnectionDetail"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointId"))) + { + this.RemotePrivateEndpointId = (string)(this.MyInvocation?.BoundParameters["RemotePrivateEndpointId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointPrivateLinkServiceConnection"))) + { + this.RemotePrivateEndpointPrivateLinkServiceConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointPrivateLinkServiceConnection"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointManualPrivateLinkServiceConnection"))) + { + this.RemotePrivateEndpointManualPrivateLinkServiceConnection = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceConnection[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointManualPrivateLinkServiceConnection"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("RemotePrivateEndpointPrivateLinkServiceProxy"))) + { + this.RemotePrivateEndpointPrivateLinkServiceProxy = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IPrivateLinkServiceProxy[])(this.MyInvocation?.BoundParameters["RemotePrivateEndpointPrivateLinkServiceProxy"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + /// 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.RecoveryServicesDataReplication.Models.IPrivateEndpointConnectionProxy + 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/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded.cs new file mode 100644 index 00000000000..d8e9209f7c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the protected item. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Protected item model update. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelUpdate(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ProtectedItemModelCustomPropertiesUpdate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ProtectedItemModelCustomPropertiesUpdate.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _propertiesBody.CustomPropertyInstanceType ?? null; set => _propertiesBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationProtectedItem_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.VaultName = this.VaultName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemUpdate(SubscriptionId, ResourceGroupName, VaultName, Name, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..93ab78399bf --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded.cs @@ -0,0 +1,556 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the protected item. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Protected item model update. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelUpdate(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ProtectedItemModelCustomPropertiesUpdate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ProtectedItemModelCustomPropertiesUpdate.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _propertiesBody.CustomPropertyInstanceType ?? null; set => _propertiesBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationProtectedItem_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProtectedItemUpdateViaIdentity(InputObject.Id, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProtectedItemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProtectedItemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProtectedItemUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, InputObject.ProtectedItemName ?? null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded.cs new file mode 100644 index 00000000000..b46c6d4e48c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded.cs @@ -0,0 +1,569 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the protected item. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + public partial class UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Protected item model update. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModelUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ProtectedItemModelUpdate(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.ClientAPI; + + /// Discriminator property for ProtectedItemModelCustomPropertiesUpdate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Discriminator property for ProtectedItemModelCustomPropertiesUpdate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Discriminator property for ProtectedItemModelCustomPropertiesUpdate.", + SerializedName = @"instanceType", + PossibleTypes = new [] { typeof(string) })] + public string CustomPropertyInstanceType { get => _propertiesBody.CustomPropertyInstanceType ?? null; set => _propertiesBody.CustomPropertyInstanceType = 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _replicationVaultInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity ReplicationVaultInputObject { get => this._replicationVaultInputObject; set => this._replicationVaultInputObject = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded(); + 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.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (ReplicationVaultInputObject?.Id != null) + { + this.ReplicationVaultInputObject.Id += $"/protectedItems/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.ProtectedItemUpdateViaIdentity(ReplicationVaultInputObject.Id, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == ReplicationVaultInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + if (null == ReplicationVaultInputObject.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("ReplicationVaultInputObject has null value for ReplicationVaultInputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, ReplicationVaultInputObject) ); + } + await this.Client.ProtectedItemUpdate(ReplicationVaultInputObject.SubscriptionId ?? null, ReplicationVaultInputObject.ResourceGroupName ?? null, ReplicationVaultInputObject.VaultName ?? null, Name, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaIdentityReplicationVaultExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..8048d20dca2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath.cs @@ -0,0 +1,592 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the protected item. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + public global::System.String _jsonString; + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationProtectedItem_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemUpdateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString.cs new file mode 100644 index 00000000000..f486817ec51 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString.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.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// Performs update on the protected item. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IProtectedItemModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"Performs update on the protected item.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}/protectedItems/{protectedItemName}", ApiVersion = "2024-09-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.NotSuggestDefaultParameterSet] + public partial class UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The protected item name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The protected item name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The protected item name.", + SerializedName = @"protectedItemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProtectedItemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationProtectedItem_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.VaultName = this.VaultName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProtectedItemUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProtectedItemUpdateViaJsonString(SubscriptionId, ResourceGroupName, VaultName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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,VaultName=VaultName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationProtectedItem_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IProtectedItemModel + /// 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.RecoveryServicesDataReplication.Models.IProtectedItemModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded.cs new file mode 100644 index 00000000000..5c34d69afc6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded.cs @@ -0,0 +1,652 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationVault_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Vault model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The vault name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The vault name.")] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("VaultName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags 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; } + + /// Gets or sets the type of vault. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the type of vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the type of vault.", + SerializedName = @"vaultType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + public string VaultType { get => _resourceBody.VaultType ?? null; set => _resourceBody.VaultType = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.VaultGetWithResult(SubscriptionId, ResourceGroupName, Name, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.VaultCreate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationVault_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("VaultType"))) + { + this.VaultType = (string)(this.MyInvocation?.BoundParameters["VaultType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..0106119b093 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/cmdlets/UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded.cs @@ -0,0 +1,633 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Cmdlets; + using System; + + /// update the vault. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataReplication/replicationVaults/{vaultName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel))] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Description(@"update the vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Generated] + public partial class UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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(); + + /// Vault model. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IVaultModel _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.VaultModel(); + + /// 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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.IRecoveryServicesDataReplicationIdentity 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.RecoveryServicesDataReplication.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags 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; } + + /// Gets or sets the type of vault. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Gets or sets the type of vault.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Category(global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets or sets the type of vault.", + SerializedName = @"vaultType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.PSArgumentCompleterAttribute("DisasterRecovery", "Migrate")] + public string VaultType { get => _resourceBody.VaultType ?? null; set => _resourceBody.VaultType = 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Cmdlets.UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzRecoveryServicesDataReplicationVault_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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.VaultGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.VaultCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.VaultName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.VaultName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.VaultGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.VaultCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.VaultName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public UpdateAzRecoveryServicesDataReplicationVault_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Models.ITrackedResourceTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("VaultType"))) + { + this.VaultType = (string)(this.MyInvocation?.BoundParameters["VaultType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Models.IVaultModel + /// 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.RecoveryServicesDataReplication.Models.IVaultModel + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..4f8097f4ec3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..3f3c2a272a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..cc0bd7abc8e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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/DataReplication.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..4eb42255b29 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication +{ + 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/DataReplication.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..febc52d2e71 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication +{ + 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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..86ee7f4ce8b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..a8f9d431c30 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..fe2646c419f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..57fa3449619 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..bcb0bca549a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..8dc76de5109 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..07a5038f0c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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: RecoveryServicesDataReplication 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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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 RecoveryServicesDataReplication".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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..6f3348583d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..84c6e2158fa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..4c75dc629b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..354a86f551a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..2f48518bf2f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..0840e4673ed --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..b3b5a250731 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..ca87d0ee9ba --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..78fa7600324 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,211 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.RecoveryServicesDataReplication.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 static string CapitalizeFirstLetter(string text) + { + if (string.IsNullOrEmpty(text)) + return text; + + return char.ToUpper(text[0]) + text.Substring(1); + } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = CapitalizeFirstLetter(helpObject.GetProperty("Synopsis")); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + Description = CapitalizeFirstLetter(Description); + 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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..d6632f6a87a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..ccd6a79858d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,681 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetLoginVerification() + { + if (!VariantGroup.IsInternal && IsAzure && !VariantGroup.IsModelCmdlet) + { + return $@" +{Indent}{Indent}$context = Get-AzContext +{Indent}{Indent}if (-not $context -and -not $testPlayback) {{ +{Indent}{Indent}{Indent}Write-Error ""No Azure login detected. Please run 'Connect-AzAccount' to log in."" +{Indent}{Indent}{Indent}exit +{Indent}{Indent}}} +"; + } + return ""; + } + + 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.RecoveryServicesDataReplication.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 +{Indent}{Indent} +{Indent}{Indent}$testPlayback = $false +{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }} +{GetLoginVerification()}{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}if ($wrappedCmd -eq $null) {{ +{Indent}{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Function) +{Indent}{Indent}}} +{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}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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..f6d882ca027 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,549 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 bool IsModelCmdlet { 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; + IsModelCmdlet = Variants.All(v => v.IsModelCmdlet); + 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 IsModelCmdlet { 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(); + IsModelCmdlet = 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(); + Description = PsHelpInfo.CapitalizeFirstLetter(Description); + // 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/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..1de26d6ab7c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,136 @@ +/*--------------------------------------------------------------------------------------------- + * 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.RecoveryServicesDataReplication +{ + [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 | AttributeTargets.Property)] + public class ModelCmdletAttribute : 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/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..8b23d9366e1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..42e4d6d52ad --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..478220649f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..2a38a20ade0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..89e74c2a83a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..d3c2e99fbb3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParameters, 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.RecoveryServicesDataReplication.AzureSiteRecoveryManagementServiceApi Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..cb9f942b935 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..3bd168d3247 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..a1bfcc503b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..f418512c511 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..87dc44b5103 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..8cd6f952ce7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..d363e984184 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..0c575531ad1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..095407fd1c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..c40a29b9997 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..bff5e04c737 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..5b0d7e69a3d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..025c8345ed7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..bb89806e308 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..dddc7276d1d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..63069a3c9aa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..4d5300d902b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..371fe699dec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..2b7ab76213c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..fc8baf51e77 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..323635bc271 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..00ecc97cc28 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..388ebd7e11d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..410813ec30a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..c3af1d18f89 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..35a2b49dec0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..cc6edd2ec2f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..cdc4faf395f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..3c49de6f4df --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..e09b63190b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..b84956551ca --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..2598e37f41b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..64586388b54 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..e127a5456bb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..0c3efde46e3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..73f0925c918 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..9ee39784b7d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..0e3d217c9bd --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..e43c0cc173f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..c30a4466046 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..1c132150582 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..f629cd73086 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..adc2599c32a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..a845b9df4c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..ebc1d625dfe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..ccc95ef5e83 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..9267d42a911 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..db85c772711 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..ba79d87ff64 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..551f7f3d6f5 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..2dc84dc35eb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..15a6d44d6a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..28fb9fed5d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..8338d8dc277 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..91797b7de4b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..927f5946c39 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..29c916c11c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..0b7d86ad525 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,353 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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 description of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //Name of the module that is being deprecated + public string moduleName { get; set; } = String.IsNullOrEmpty(@"") ? @"Az.RecoveryServicesDataReplication" : @""; + + //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.moduleName, 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/DataReplication.Management.brown/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..30bb62b12ae --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..3791aa78e11 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..5a37f077652 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..8ef241b94db --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..c264bacb6c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..8b6a824e9e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..a9755611667 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..15106861a9e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..8456164c2d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..04104267db9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..c75a9a6a484 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..f306ec74b21 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..4900451a9b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..7f53f05d0f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..b24e75e44f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..002dacd2e96 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..1f8e9732044 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..cf73ae92dd3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..7a3d5979588 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..d55b0f5ae13 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..7850e36bffe --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..072a5d450f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..0dff417e91c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..c0d06596f5d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..4435cbf3b3b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..28f5b2cf2e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..dcb30bfde5c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..4ef90b70573 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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 in '{0}' from version : '{1}' + + + ```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/DataReplication.Management.brown/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..5c34ea6f1bb --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..f9f47c9bd55 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..4756e42e5cc --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..a3e535a7153 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..e666d5ede1a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..4c2b77e7ec4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..b620a4a979c --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..faeec472cb1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..c0bc54e736b --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/how-to.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/how-to.md new file mode 100644 index 00000000000..bc252df4da6 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.RecoveryServicesDataReplication`. + +## Building `Az.RecoveryServicesDataReplication` +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.RecoveryServicesDataReplication` +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.RecoveryServicesDataReplication` +To pack `Az.RecoveryServicesDataReplication` 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.RecoveryServicesDataReplication`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.RecoveryServicesDataReplication.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.RecoveryServicesDataReplication.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.RecoveryServicesDataReplication`. + - `-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.RecoveryServicesDataReplication` 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/DataReplication.Management.brown/target/internal/Az.RecoveryServicesDataReplication.internal.psm1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/internal/Az.RecoveryServicesDataReplication.internal.psm1 new file mode 100644 index 00000000000..f7b7806944f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/internal/Az.RecoveryServicesDataReplication.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.RecoveryServicesDataReplication.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/internal/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/internal/README.md new file mode 100644 index 00000000000..5acc5bcb746 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.RecoveryServicesDataReplication`. Instead, this sub-module is imported by the `..\custom\Az.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication.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.RecoveryServicesDataReplication`. diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/license.txt b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/pack-module.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/resources/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/run-module.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/run-module.ps1 new file mode 100644 index 00000000000..ed392cdb4c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/test-module.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/test-module.ps1 new file mode 100644 index 00000000000..75a3d80bdb4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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.RecoveryServicesDataReplication.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/DataReplication.Management.brown/target/test/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/README.md new file mode 100644 index 00000000000..d28996846ef --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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: + - https://github.com/Azure/azure-rest-api-specs/blob/d55f30f41f04e712de101fc9c17a591ca410bfed/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/DataReplication.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/DataReplication.Management.brown/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/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/DataReplication.Management.brown/tspconfig.yaml b/tests-upgrade/tests-emitter/DataReplication.Management.brown/tspconfig.yaml new file mode 100644 index 00000000000..931b82001fa --- /dev/null +++ b/tests-upgrade/tests-emitter/DataReplication.Management.brown/tspconfig.yaml @@ -0,0 +1,85 @@ +parameters: + "service-dir": + default: "sdk/recoveryservicesdatareplication" +emit: + - "@azure-tools/typespec-autorest" +options: + "@azure-tools/typespec-autorest": + use-read-only-status-schema: true + omit-unreachable-types: true + emitter-output-dir: "{project-root}/.." + azure-resource-provider-folder: "resource-manager" + output-file: "{azure-resource-provider-folder}/{service-name}/{version-status}/{version}/recoveryservicesdatareplication.json" + examples-dir: "{project-root}/examples" + "@azure-tools/typespec-csharp": + flavor: azure + package-dir: "Azure.ResourceManager.RecoveryServicesDataReplication" + clear-output-folder: true + model-namespace: false + namespace: "{package-dir}" + service-dir: "sdk/recoveryservices-datareplication" + "@azure-tools/typespec-python": + package-dir: "azure-mgmt-recoveryservicesdatareplication" + namespace: "azure.mgmt.recoveryservicesdatareplication" + flavor: "azure" + generate-test: true + generate-sample: true + "@azure-tools/typespec-go": + service-dir: "sdk/resourcemanager/recoveryservicesdatareplication" + package-dir: "armrecoveryservicesdatareplication" + 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 + "@azure-tools/typespec-java": + package-dir: "azure-resourcemanager-recoveryservicesdatareplication" + flavor: "azure" + namespace: "com.azure.resourcemanager.recoveryservicesdatareplication" + service-name: "Recovery Services Data Replication" + rename-model: + PrivateEndpointConnectionProxyListResult: "PrivEdpConnProxyListResult" + PrivateEndpointConnectionListResult: "PrivEdpConnListResult" + ReplicationExtensionModelListResult: "RepExtModelListResult" + JobModelCustomPropertiesAffectedObjectDetailsType: "AffectedObjectDetailsType" + "@azure-tools/typespec-ts": + typespec-title-map: + DataReplicationClient: AzureSiteRecoveryManagementServiceAPI + experimental-extensible-enums: true + package-dir: "arm-recoveryservicesdatareplication" + flavor: "azure" + package-details: + name: "@azure/arm-recoveryservicesdatareplication" + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "RecoveryServicesDataReplication/RecoveryServicesDataReplication.Autorest" + clear-output-folder: true + azure: true + module-version: 0.1.0 + prefix: 'Az' + subject-prefix: 'RecoveryServicesDataReplication' + service-name: RecoveryServicesDataReplication + module-name: "{prefix}.{service-name}" + 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: + variant: ^CreateViaIdentity.*$ + remove: true +linter: + extends: + - "@azure-tools/typespec-azure-rulesets/resource-manager" diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/README.md new file mode 100644 index 00000000000..5b016419d7e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/README.md @@ -0,0 +1,24 @@ +# Fleet service cadl project + +## Getting started + +- environment setup: https://microsoft.github.io/typespec/introduction/installation + +## Generate fleet swagger + +## NPM registry authentication + +We have to use the Central Feed Service for NPM to fetch the typespec dependencies. +The `.npmrc` file configures the folder accordingly for CI. + +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. diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/client.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/client.tsp new file mode 100644 index 00000000000..758c48c9f12 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/client.tsp @@ -0,0 +1,57 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; + +@@clientName(Microsoft.ContainerService, + "ContainerServiceFleetManagementClient", + "java" +); + +@@clientName(Microsoft.ContainerService, + "ContainerServiceFleetMgmtClient", + "python" +); + +@@clientName(Microsoft.ContainerService.APIServerAccessProfile, + "ApiServerAccessProfile", + "java" +); +@@clientName(Azure.ResourceManager.EntityTagProperty.eTag, "etag", "java"); + +#suppress "@azure-tools/typespec-azure-core/no-legacy-usage" "Existing usage of legacy type" +@@clientName(Azure.ResourceManager.Legacy.ManagedServiceIdentityV4, + "ManagedServiceIdentity" +); +#suppress "@azure-tools/typespec-azure-core/no-legacy-usage" "Existing usage of legacy type" +@@clientName(Azure.ResourceManager.Legacy.ManagedServiceIdentityType.SystemAndUserAssigned, + "SYSTEM_ASSIGNED_USER_ASSIGNED", + "python" +); +@@clientName(Microsoft.ContainerService.FleetMembers.updateAsync, + "begin_update", + "python" +); +@@clientName(Microsoft.ContainerService.Fleets.create, + "begin_create_or_update", + "python" +); +@@clientName(Microsoft.ContainerService.Fleets.updateAsync, + "begin_update", + "python" +); + +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(Azure.ResourceManager.TrackedResource.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(Azure.ResourceManager.ProxyResource.properties); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(Azure.ResourceManager.Foundations.ResourceUpdateModel.properties +); +#suppress "deprecated" "property flatten for SDK backward compatibility" +@@flattenProperty(Azure.ResourceManager.Foundations.ProxyResourceUpdateModel.properties +); +@@clientName(Microsoft.ContainerService, + "ContainerServiceFleetClient", + "javascript" +); diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/fleet.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/fleet.tsp new file mode 100644 index 00000000000..80f78b065c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/fleet.tsp @@ -0,0 +1,265 @@ +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./helpers.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.ResourceManager; +using Azure.Core; +using Azure.Core.Traits; +using TypeSpec.OpenAPI; + +namespace Microsoft.ContainerService; + +@doc("The Fleet resource.") +@resource("fleets") +model Fleet is TrackedResource { + @doc("The name of the Fleet resource.") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(63) + @key("fleetName") + @path + @segment("fleets") + @visibility(Lifecycle.Create, Lifecycle.Read) + name: string; + + ...EntityTagProperty; + + #suppress "@azure-tools/typespec-azure-core/no-legacy-usage" "Existing usage of legacy type" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "https://github.com/Azure/typespec-azure/issues/2840" + @added(Versions.v2023_06_15_preview) + @doc("Managed identity.") + identity?: Azure.ResourceManager.Legacy.ManagedServiceIdentityV4; +} + +@doc("Fleet properties.") +model FleetProperties { + // adding a response header in the model currently impacts the model used in the List result model. + // omitting it for now as response headers do not impact SDK generation. + // ...EtagResponseEnvelope; + + @visibility(Lifecycle.Read) + @doc("The status of the last operation.") + provisioningState?: FleetProvisioningState; + + #suppress "@azure-tools/typespec-providerhub/non-breaking-versioning" "https://github.com/Azure/typespec-azure/issues/3558" + @doc("The FleetHubProfile configures the Fleet's hub.") + @added(Versions.v2022_09_02_preview) + @added(Versions.v2023_03_15_preview) + @added(Versions.v2023_06_15_preview) + @added(Versions.v2023_08_15_preview) + @removed(Versions.v2023_10_15) + @added(Versions.v2024_02_02_preview) + @added(Versions.v2024_04_01) + hubProfile?: FleetHubProfile; + + @added(Versions.v2025_03_01) + @visibility(Lifecycle.Read) + @doc("Status information for the fleet.") + status?: FleetStatus; +} + +@doc("The FleetHubProfile configures the fleet hub.") +model FleetHubProfile { + @doc("DNS prefix used to create the FQDN for the Fleet hub.") + @visibility(Lifecycle.Read, Lifecycle.Create) + @pattern("^[a-zA-Z0-9]$|^[a-zA-Z0-9][a-zA-Z0-9-]{0,52}[a-zA-Z0-9]$") + @minLength(1) + @maxLength(54) + dnsPrefix?: string; + + @added(Versions.v2023_06_15_preview) + @doc("The access profile for the Fleet hub API server.") + @visibility(Lifecycle.Read, Lifecycle.Create) + apiServerAccessProfile?: APIServerAccessProfile; + + @added(Versions.v2023_06_15_preview) + @doc("The agent profile for the Fleet hub.") + @visibility(Lifecycle.Read, Lifecycle.Create) + agentProfile?: AgentProfile; + + @visibility(Lifecycle.Read) + @doc("The FQDN of the Fleet hub.") + fqdn?: string; + + @visibility(Lifecycle.Read) + @doc("The Kubernetes version of the Fleet hub.") + kubernetesVersion?: string; + + @added(Versions.v2023_08_15_preview) + @visibility(Lifecycle.Read) + @doc("The Azure Portal FQDN of the Fleet hub.") + portalFqdn?: string; +} + +scalar SubnetResourceId + extends Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.Network/virtualNetworks/subnets", + } + ]>; + +#suppress "@azure-tools/typespec-azure-core/casing-style" "match existing AKS APIServerAccessProfile" +@doc("Access profile for the Fleet hub API server.") +model APIServerAccessProfile { + @visibility(Lifecycle.Read, Lifecycle.Create) + @doc("Whether to create the Fleet hub as a private cluster or not.") + enablePrivateCluster?: boolean; + + @visibility(Lifecycle.Read, Lifecycle.Create) + @added(Versions.v2023_06_15_preview) + @removed(Versions.v2024_04_01) + @added(Versions.v2024_05_02_preview) + @doc("Whether to enable apiserver vnet integration for the Fleet hub or not.") + enableVnetIntegration?: boolean; + + @visibility(Lifecycle.Read, Lifecycle.Create) + @added(Versions.v2023_06_15_preview) + @removed(Versions.v2024_04_01) + @added(Versions.v2024_05_02_preview) + @doc("The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.") + subnetId?: SubnetResourceId; +} + +@doc("Agent profile for the Fleet hub.") +model AgentProfile { + @visibility(Lifecycle.Read, Lifecycle.Create) + @doc("The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.") + subnetId?: SubnetResourceId; + + @added(Versions.v2023_08_15_preview) + @doc("The virtual machine size of the Fleet hub.") + @visibility(Lifecycle.Read, Lifecycle.Create) + vmSize?: string; +} + +@lroStatus +@doc("The provisioning state of the last accepted operation.") +union FleetProvisioningState { + string, + ResourceProvisioningState, + + @doc("The provisioning state of a fleet being created.") + Creating: "Creating", + + @doc("The provisioning state of a fleet being updated.") + Updating: "Updating", + + @doc("The provisioning state of a fleet being deleted.") + Deleting: "Deleting", +} + +@doc("Properties of a Fleet that can be patched.") +model FleetPatch { + // adding a response header in the model currently impacts the model used in the List result model. + // omitting it for now as response headers do not impact SDK generation. + // ...EtagResponseEnvelope; + ...Azure.ResourceManager.Foundations.ArmTagsProperty; + + #suppress "@azure-tools/typespec-azure-core/no-legacy-usage" "Existing usage of legacy type" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "https://github.com/Azure/typespec-azure/issues/2840" + @added(Versions.v2023_06_15_preview) + @doc("Managed identity.") + identity?: Azure.ResourceManager.Legacy.ManagedServiceIdentityV4; +} + +@doc("One credential result item.") +model FleetCredentialResult { + @visibility(Lifecycle.Read) + @doc("The name of the credential.") + name?: string; + + @visibility(Lifecycle.Read) + @doc("Base64-encoded Kubernetes configuration file.") + value?: bytes; +} + +@doc("The Credential results response.") +model FleetCredentialResults { + @visibility(Lifecycle.Read) + @doc("Array of base64-encoded Kubernetes configuration files.") + @identifiers(#["name"]) + kubeconfigs?: FleetCredentialResult[]; +} + +@added(Versions.v2025_03_01) +@doc("Status information for the fleet.") +model FleetStatus { + @visibility(Lifecycle.Read) + @doc("The last operation ID for the fleet.") + lastOperationId?: string; + + @visibility(Lifecycle.Read) + @doc("The last operation error for the fleet.") + lastOperationError?: Azure.ResourceManager.Foundations.ErrorDetail; +} + +@armResourceOperations +interface Fleets { + @doc("Gets a Fleet.") + get is ArmResourceRead; + + #suppress "@azure-tools/typespec-azure-core/invalid-final-state" "must change at next update" + #suppress "@azure-tools/typespec-azure-core/no-openapi" "changing the operation-id on an existing operation is an SDK breaking change" + @doc("Creates or updates a Fleet.") + @operationId("Fleets_CreateOrUpdate") + @Azure.Core.useFinalStateVia("azure-async-operation") + create is ArmResourceCreateOrUpdateAsync< + Fleet, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters & + IfNoneMatchParameters, + LroHeaders = Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "@azure-tools/typespec-providerhub/non-breaking-versioning" "Actual breaking change" + @sharedRoute + @removed(Versions.v2023_06_15_preview) + update is ArmCustomPatchSync< + Fleet, + FleetPatch, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Use operationId to keep same name as deprecated sync operation" + @added(Versions.v2023_06_15_preview) + @operationId("Fleets_Update") + // @extension( + // "x-ms-long-running-operation-options", + // #{ `final-state-via`: "original-uri" } + // ) + @sharedRoute + @useFinalStateVia("azure-async-operation") + updateAsync is ArmCustomPatchAsync< + Fleet, + FleetPatch, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters, + LroHeaders = ArmAsyncOperationHeader & Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "deprecated" "Existing API" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-delete-operation-response-codes" "Existing API" + @sharedRoute // why do we need to set shared route on delete? compiler complains with an error + // All shared routes must agree on the value of the shared parameter.TypeSpec(@typespec/http/shared-inconsistency) + delete is ArmResourceDeleteAsync< + Fleet, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + @doc("Lists fleets in the specified subscription and resource group.") + listByResourceGroup is ArmResourceListByParent; + + @doc("Lists fleets in the specified subscription.") + listBySubscription is ArmListBySubscription; + + @doc("Lists the user credentials of a Fleet.") + listCredentials is ArmResourceActionSync; +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/fleetmember.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/fleetmember.tsp new file mode 100644 index 00000000000..d5d6ac9613a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/fleetmember.tsp @@ -0,0 +1,157 @@ +import "@typespec/rest"; +import "./helpers.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.Core; +using Azure.ResourceManager; +using TypeSpec.OpenAPI; + +namespace Microsoft.ContainerService; + +@doc("A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure.") +@resource("members") +@parentResource(Fleet) +model FleetMember is ProxyResource { + @doc("The name of the Fleet member resource.") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + @key("fleetMemberName") + @path + @segment("members") + @visibility(Lifecycle.Create, Lifecycle.Read) + name: string; + + ...EntityTagProperty; +} + +scalar ClusterResourceId + extends Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.ContainerService/managedClusters", + } + ]>; + +@doc("A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure.") +model FleetMemberProperties { + // adding a response header in the model currently impacts the model used in the List result model. + // omitting it for now as response headers do not impact SDK generation. + // ...EtagResponseEnvelope; + + @visibility(Lifecycle.Create, Lifecycle.Read) + @doc("The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'.") + clusterResourceId: ClusterResourceId; + + @doc("The group this member belongs to for multi-cluster update management.") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + @added(Versions.v2023_03_15_preview) + group?: string; + + @visibility(Lifecycle.Read) + @doc("The status of the last operation.") + provisioningState?: FleetMemberProvisioningState; + + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "Records is the most semantically correct choice for this use-case" + @added(Versions.v2025_04_01_preview) + @doc("The labels for the fleet member.") + labels?: Record; + + @added(Versions.v2025_03_01) + @visibility(Lifecycle.Read) + @doc("Status information of the last operation for fleet member.") + status?: FleetMemberStatus; +} + +@added(Versions.v2025_03_01) +@doc("Status information for the fleet member") +model FleetMemberStatus { + @visibility(Lifecycle.Read) + @doc("The last operation ID for the fleet member") + lastOperationId?: string; + + @visibility(Lifecycle.Read) + @doc("The last operation error of the fleet member") + lastOperationError?: Azure.ResourceManager.Foundations.ErrorDetail; +} + +@lroStatus +@doc("The provisioning state of the last accepted operation.") +union FleetMemberProvisioningState { + string, + ResourceProvisioningState, + + @doc("The provisioning state of a member joining a fleet.") + Joining: "Joining", + + @doc("The provisioning state of a member leaving a fleet.") + Leaving: "Leaving", + + @doc("The provisioning state of a member being updated.") + Updating: "Updating", +} + +@armResourceOperations +interface FleetMembers { + get is ArmResourceRead; + + #suppress "@azure-tools/typespec-azure-core/invalid-final-state" "must change at next release" + @Azure.Core.useFinalStateVia("azure-async-operation") + create is ArmResourceCreateOrUpdateAsync< + FleetMember, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters & + IfNoneMatchParameters, + LroHeaders = Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "@azure-tools/typespec-providerhub/non-breaking-versioning" "Actual breaking change" + @sharedRoute + @added(Versions.v2023_03_15_preview) + @removed(Versions.v2023_06_15_preview) + update is ArmCustomPatchSync< + FleetMember, + Azure.ResourceManager.Foundations.ResourceUpdateModel< + FleetMember, + FleetMemberProperties + >, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Use operationId to keep same name as deprecated sync operation" + @sharedRoute + @added(Versions.v2023_06_15_preview) + @operationId("FleetMembers_Update") + // @extension( + // "x-ms-long-running-operation-options", + // #{ `final-state-via`: "original-uri" } + // ) + @useFinalStateVia("azure-async-operation") + updateAsync is ArmCustomPatchAsync< + FleetMember, + Azure.ResourceManager.Foundations.ResourceUpdateModel< + FleetMember, + FleetMemberProperties + >, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters, + LroHeaders = ArmAsyncOperationHeader & Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "deprecated" "Existing API" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-delete-operation-response-codes" "Existing API" + @sharedRoute // why do we need to set shared route on delete? compiler complains with an error + // All shared routes must agree on the value of the shared parameter.TypeSpec(@typespec/http/shared-inconsistency) + delete is ArmResourceDeleteAsync< + FleetMember, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + /** List FleetMember resources by Fleet */ + listByFleet is ArmResourceListByParent; +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/gate.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/gate.tsp new file mode 100644 index 00000000000..80924f15322 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/gate.tsp @@ -0,0 +1,199 @@ +import "@typespec/rest"; +import "./helpers.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.Core; +using Azure.ResourceManager; +using TypeSpec.OpenAPI; + +namespace Microsoft.ContainerService; + +@doc("A Gate controls the progression during a staged rollout, e.g. in an Update Run.") +@added(Versions.v2025_04_01_preview) +@resource("gates") +@parentResource(Fleet) +model Gate is ProxyResource { + @doc("The name of the Gate resource, a GUID.") + @pattern("^[0-9a-f]{8}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{12}$") + @minLength(36) + @maxLength(36) + @key("gateName") + @path + @segment("gates") + @visibility(Lifecycle.Read) + name: string; + + ...EntityTagProperty; +} + +@doc("The type of the Gate determines how it is completed.") +@added(Versions.v2025_04_01_preview) +union GateType { + string, + + @doc("An approval gate is completed by setting its state to be Completed.") + Approval: "Approval", +} + +@doc("The state of the Gate.") +@added(Versions.v2025_04_01_preview) +union GateState { + string, + + @doc("A Pending Gate will continue to block the staged rollout process it is controlling.") + Pending: "Pending", + + @doc("A Skipped Gate means that the staged rollout process it is controlling was skipped.") + Skipped: "Skipped", + + @doc("An Completed Gate allows the staged rollout process to continue.") + Completed: "Completed", +} + +@doc("A Gate controls the progression during a staged rollout, e.g. in an Update Run.") +@added(Versions.v2025_04_01_preview) +model GateProperties { + // adding a response header in the model currently impacts the model used in the List result model. + // omitting it for now as response headers do not impact SDK generation. + // ...EtagResponseEnvelope; + + @doc("The provisioning state of the Gate resource.") + @visibility(Lifecycle.Read) + provisioningState?: GateProvisioningState; + + @doc("The human-readable display name of the Gate.") + @visibility(Lifecycle.Create, Lifecycle.Read) + @minLength(1) + @maxLength(100) + displayName?: string; + + @doc("The type of the Gate determines how it is completed.") + @visibility(Lifecycle.Create, Lifecycle.Read) + gateType: GateType; + + @doc("The target that the Gate is controlling, e.g. an Update Run.") + @visibility(Lifecycle.Create, Lifecycle.Read) + target: GateTarget; + + @doc("The state of the Gate.") + @visibility(Lifecycle.Create, Lifecycle.Update, Lifecycle.Read) + state: GateState; +} + +@doc("The type of the Gate target.") +@added(Versions.v2025_04_01_preview) +union GateTargetType { + string, + + @doc("The Gate targets an Update Run.") + UpdateRun: "UpdateRun", +} + +@doc("The properties of the Update Run that the Gate is targeting.") +@added(Versions.v2025_04_01_preview) +model UpdateRunGateTargetProperties { + @doc("The name of the Update Run.") + @visibility(Lifecycle.Read) + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + name: string; + + @doc("The Update Stage of the Update Run.") + @visibility(Lifecycle.Read) + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + stage?: string; + + @doc("The Update Group of the Update Run.") + @visibility(Lifecycle.Read) + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + group?: string; + + @doc("Whether the Gate is placed before or after the update itself.") + @visibility(Lifecycle.Create, Lifecycle.Read) + timing: Timing; +} + +@doc("Whether the Gate is placed before or after the target.") +@added(Versions.v2025_04_01_preview) +union Timing { + string, + + @doc("The Gate is before the target.") + Before: "Before", + + @doc("The Gate is after the target.") + After: "After", +} + +scalar UpdateRunResourceId + extends Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.ContainerService/fleets/updateRuns", + } + ]>; + +alias GateTargetId = UpdateRunResourceId; + +@doc("The target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set.") +@added(Versions.v2025_04_01_preview) +model GateTarget { + @doc("The resource id that the Gate is controlling the rollout of.") + @visibility(Lifecycle.Create, Lifecycle.Read) + id: GateTargetId; + + @doc("The properties of the Update Run that the Gate is targeting.") + @visibility(Lifecycle.Create, Lifecycle.Read) + updateRunProperties?: UpdateRunGateTargetProperties; +} + +@doc("The provisioning state of the Gate resource.") +@lroStatus +union GateProvisioningState { + string, + ResourceProvisioningState, +} + +@doc("Patch a Gate resource.") +@added(Versions.v2025_04_01_preview) +model GatePatch { + // adding a response header in the model currently impacts the model used in the List result model. + // omitting it for now as response headers do not impact SDK generation. + // ...EtagResponseEnvelope; + + @doc("Properties of a Gate that can be patched.") + properties: GatePatchProperties; +} + +@doc("Properties of a Gate that can be patched.") +@added(Versions.v2025_04_01_preview) +model GatePatchProperties { + @doc("The state of the Gate.") + state: GateState; +} + +@armResourceOperations +@added(Versions.v2025_04_01_preview) +interface Gates { + get is ArmResourceRead; + + // The create and delete APIs are both internal-only as Gates are created by the Update Run during + // its processing. As such, we only expose the update API here. + #suppress "@azure-tools/typespec-azure-core/invalid-final-state" "must change at next release" + @Azure.Core.useFinalStateVia("azure-async-operation") + update is ArmCustomPatchAsync< + Gate, + GatePatch, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters & + IfNoneMatchParameters + >; + + listByFleet is ArmResourceListByParent; +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/helpers.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/helpers.tsp new file mode 100644 index 00000000000..06c5299b878 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/helpers.tsp @@ -0,0 +1,88 @@ +import "@typespec/rest"; + +using TypeSpec.OpenAPI; +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; + +namespace Microsoft.ContainerService; + +// #suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-invalid-envelope-property" "built-in conditional request includes time based conditional headers" +alias IfMatchParameters = { + @header("If-Match") + @doc("The request should only proceed if an entity matches this string.") + ifMatch?: string; +}; + +alias IfNoneMatchParameters = { + @header("If-None-Match") + @doc("The request should only proceed if no entity matches this string.") + ifNoneMatch?: string; +}; + +alias IfMatchHeadersParameters = { + ...IfMatchParameters; + ...IfNoneMatchParameters; +}; + +#suppress "@azure-tools/cadl-azure-resource-manager/arm-resource-operation-outside-interface" "this is a template" +@autoRoute +@doc("Update a {name}", TResource) +@armResourceUpdate(TResource) +@patch(#{ implicitOptionality: true }) +op FleetCustomPatchSync< + TResource extends Foundations.Resource, + TPatchModel extends TypeSpec.Reflection.Model = TagsUpdateModel, + TBaseParameters = BaseParameters +>( + ...ResourceInstanceParameters, + + @doc("The resource properties to be updated.") + @bodyRoot + parameters?: TPatchModel, //prevents api breaking change. properties -> parameters +): ArmResponse | ErrorResponse; + +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-operation-outside-interface" "this is a template" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "DO NOT COPY - TODO migrate to LRO apis" +@autoRoute +@doc("Create a {name}", TResource) +// @extension("x-ms-long-running-operation", true) +// @extension( +// "x-ms-long-running-operation-options", +// #{ `final-state-via`: "azure-async-operation" } +// ) +@armResourceCreateOrUpdate(TResource) +@put +op FleetArmResourceCreateOrUpdateAsync< + TResource extends Azure.ResourceManager.Foundations.Resource, + TBaseParameters = BaseParameters +>( + ...ResourceInstanceParameters, + + @doc("Resource create parameters.") + @bodyRoot + parameters: TResource, //prevent api breaking change. resource -> parameters +): ArmResponse | ArmCreatedResponse | ErrorResponse; + +// this is a copy of ArmResourceDeleteAsync that adds the location header to comply with arm linter. +#suppress "@azure-tools/typespec-azure-resource-manager/arm-resource-operation" "this is a template" +#suppress "@azure-tools/typespec-providerhub/no-inline-model" "inlining the response with a header does not present a risk" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "DO NOT COPY - TODO migrate to LRO apis" +@autoRoute +@doc("Delete a {name}", TResource) +// @extension( +// "x-ms-long-running-operation-options", +// #{ `final-state-via`: "azure-async-operation" } +// ) +@armResourceDelete(TResource) +@delete +op FleetArmResourceDeleteAsync< + TResource extends Azure.ResourceManager.Foundations.Resource, + TBaseParameters = BaseParameters +>(...ResourceInstanceParameters): + | ArmDeletedResponse + | (ArmDeleteAcceptedResponse & ArmLroLocationHeader) + | ArmDeletedNoContentResponse + | ErrorResponse; diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/main.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/main.tsp new file mode 100644 index 00000000000..5f91f291175 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/main.tsp @@ -0,0 +1,76 @@ +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./fleet.tsp"; +import "./fleetmember.tsp"; +import "./gate.tsp"; +import "./update/common.tsp"; +import "./update/run.tsp"; +import "./update/strategy.tsp"; +import "./update/autoupgradeprofile.tsp"; + +using Azure.ResourceManager; +using TypeSpec.Http; +using TypeSpec.Versioning; +using TypeSpec.OpenAPI; + +@armProviderNamespace +@service(#{ title: "ContainerServiceFleetClient" }) +@doc("Azure Kubernetes Fleet Manager api client.") +@versioned(Versions) +namespace Microsoft.ContainerService; + +interface Operations extends Azure.ResourceManager.Operations {} + +@doc("Azure Kubernetes Fleet Manager api versions.") +enum Versions { + @doc("Azure Kubernetes Fleet Manager api version 2022-09-02-preview.") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2022_09_02_preview: "2022-09-02-preview", + + @doc("Azure Kubernetes Fleet Manager api version 2023-03-15-preview.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2023_03_15_preview: "2023-03-15-preview", + + @doc("Azure Kubernetes Fleet Manager api version 2023-06-15-preview.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2023_06_15_preview: "2023-06-15-preview", + + @doc("Azure Kubernetes Fleet Manager api version 2023-08-15-preview.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2023_08_15_preview: "2023-08-15-preview", + + @doc("Azure Kubernetes Fleet Manager api version 2023-10-15.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2023_10_15: "2023-10-15", + + @doc("Azure Kubernetes Fleet Manager api version 2024-02-02-preview.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2024_02_02_preview: "2024-02-02-preview", + + @doc("Azure Kubernetes Fleet Manager api version 2024-04-01.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2024_04_01: "2024-04-01", + + @doc("Azure Kubernetes Fleet Manager api version 2024-05-02-preview.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2024_05_02_preview: "2024-05-02-preview", + + @doc("Azure Kubernetes Fleet Manager api version 2025-03-01.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v5) + v2025_03_01: "2025-03-01", + + @doc("Azure Kubernetes Fleet Manager api version 2025-04-01-preview.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v5) + v2025_04_01_preview: "2025-04-01-preview", +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/.gitattributes b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.csproj b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.csproj new file mode 100644 index 00000000000..bc17d088ad6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.ContainerServiceFleet.private + false + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet + true + false + ./bin + $(OutputPath) + Az.ContainerServiceFleet.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/Fleet.Management.brown/target/Az.ContainerServiceFleet.nuspec b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.nuspec new file mode 100644 index 00000000000..410a5641727 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.nuspec @@ -0,0 +1,32 @@ + + + + Az.ContainerServiceFleet + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: ContainerServiceFleet cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule ContainerServiceFleet + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.psm1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.psm1 new file mode 100644 index 00000000000..10957ada3ff --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Az.ContainerServiceFleet.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.ContainerServiceFleet.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Properties/AssemblyInfo.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..616e227f78a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// 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. + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: System.Reflection.AssemblyCompanyAttribute("Microsoft")] +[assembly: System.Reflection.AssemblyCopyrightAttribute("Copyright © Microsoft")] +[assembly: System.Reflection.AssemblyProductAttribute("Microsoft Azure PowerShell")] +[assembly: System.Reflection.AssemblyTitleAttribute("Microsoft Azure PowerShell - ContainerServiceFleetClient")] +[assembly: System.Reflection.AssemblyFileVersionAttribute("0.1.0.0")] +[assembly: System.Reflection.AssemblyVersionAttribute("0.1.0.0")] +[assembly: System.Runtime.InteropServices.ComVisibleAttribute(false)] +[assembly: System.CLSCompliantAttribute(false)] \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/README.md new file mode 100644 index 00000000000..eb15a8a73bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/README.md @@ -0,0 +1,24 @@ + +# Az.ContainerServiceFleet +This directory contains the PowerShell module for the ContainerServiceFleet 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.ContainerServiceFleet`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/build-module.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/build-module.ps1 new file mode 100644 index 00000000000..c5fcc06c711 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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 -Force -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 -Force -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.ContainerServiceFleet.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.ContainerServiceFleet.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 -Force +} +$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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $internalFolder + +$psd1 = Join-Path $PSScriptRoot './Az.ContainerServiceFleet.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.ContainerServiceFleet' +$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: ContainerServiceFleet cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue -Force + } + $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.ContainerServiceFleet.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 '../../../tools/BuildScripts/AdaptAutorestModule.ps1' + $afterBuildTasksArgs = ConvertFrom-Json '{"SubModuleName":"Az.ContainerServiceFleet","ModuleRootName":"$(root-module-name)"}' -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/Fleet.Management.brown/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..e442cfb440a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/create-model-cmdlets.ps1 @@ -0,0 +1,263 @@ +# ---------------------------------------------------------------------------------- +# 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.ContainerServiceFleet' + } + $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}" + $Prefix = 'Az' + # remove duplicated module name + if ($ObjectType.StartsWith('ContainerServiceFleet')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'ContainerServiceFleet' + } + $OutputPath = Join-Path -ChildPath "New-${Prefix}${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] + 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-${Prefix}${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} { + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ModelCmdletAttribute()] + [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/Fleet.Management.brown/target/custom/Az.ContainerServiceFleet.custom.psm1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/custom/Az.ContainerServiceFleet.custom.psm1 new file mode 100644 index 00000000000..9444b7026a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/custom/Az.ContainerServiceFleet.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.ContainerServiceFleet.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.ContainerServiceFleet.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/Fleet.Management.brown/target/custom/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/custom/README.md new file mode 100644 index 00000000000..3e4bb6ef617 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.ContainerServiceFleet` 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.ContainerServiceFleet.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.ContainerServiceFleet` 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet`. 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.ContainerServiceFleet.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.ContainerServiceFleet.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.ContainerServiceFleet`. +- `Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.ContainerServiceFleet`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/docs/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/docs/README.md new file mode 100644 index 00000000000..45a0d5e64b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.ContainerServiceFleet` 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.ContainerServiceFleet` 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/Fleet.Management.brown/target/examples/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/export-surface.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/export-surface.ps1 new file mode 100644 index 00000000000..7f3099b7aac --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.ContainerServiceFleet' +$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/Fleet.Management.brown/target/exports/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/exports/README.md new file mode 100644 index 00000000000..36580ffa158 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.ContainerServiceFleet`. No other cmdlets in this repository are directly exported. What that means is the `Az.ContainerServiceFleet` 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.ContainerServiceFleet.private.dll`) and from the `..\custom\Az.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generate-help.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generate-help.ps1 new file mode 100644 index 00000000000..f29edfabf33 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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 -Force +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.ContainerServiceFleet.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.ContainerServiceFleet.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..c1639459391 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet' +$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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/Module.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/Module.cs new file mode 100644 index 00000000000..9cbe7681686 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient 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.ContainerServiceFleet.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.ContainerServiceFleet"; + + /// 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.ContainerServiceFleet"; + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/ContainerServiceFleetClient.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/ContainerServiceFleetClient.cs new file mode 100644 index 00000000000..09f7847bb95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/ContainerServiceFleetClient.cs @@ -0,0 +1,14556 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Low-level API implementation for the ContainerServiceFleetClient service. + /// Azure Kubernetes Fleet Manager api client. + /// + public partial class ContainerServiceFleetClient + { + + /// Generates an generate run for a given auto upgrade profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfileOperationsGenerateUpdateRun(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "/generateUpdateRun" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfileOperationsGenerateUpdateRun_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Generates an generate run for a given auto upgrade 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfileOperationsGenerateUpdateRunViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "/generateUpdateRun" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfileOperationsGenerateUpdateRun_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Generates an generate run for a given auto upgrade profile. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfileOperationsGenerateUpdateRunViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "/generateUpdateRun" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfileOperationsGenerateUpdateRunWithResult_Call (request, eventListener,sender); + } + } + + /// Generates an generate run for a given auto upgrade profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfileOperationsGenerateUpdateRunWithResult(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "/generateUpdateRun" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfileOperationsGenerateUpdateRunWithResult_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.ContainerServiceFleet.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 AutoUpgradeProfileOperationsGenerateUpdateRunWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GenerateResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 AutoUpgradeProfileOperationsGenerateUpdateRun_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GenerateResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile 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 AutoUpgradeProfileOperationsGenerateUpdateRun_Validate(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(autoUpgradeProfileName),autoUpgradeProfileName); + await eventListener.AssertMinimumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,1); + await eventListener.AssertMaximumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,50); + await eventListener.AssertRegEx(nameof(autoUpgradeProfileName), autoUpgradeProfileName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// update a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 AutoUpgradeProfilesCreateOrUpdate(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a AutoUpgradeProfile + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 AutoUpgradeProfilesCreateOrUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a AutoUpgradeProfile + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 AutoUpgradeProfilesCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the AutoUpgradeProfilesCreateOrUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, string ifMatch, string ifNoneMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the AutoUpgradeProfilesCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, string ifMatch, string ifNoneMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 AutoUpgradeProfilesCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesCreateOrUpdateWithResult_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.ContainerServiceFleet.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 AutoUpgradeProfilesCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 AutoUpgradeProfilesCreateOrUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile 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 AutoUpgradeProfilesCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string ifNoneMatch, string fleetName, string autoUpgradeProfileName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(ifNoneMatch),ifNoneMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(autoUpgradeProfileName),autoUpgradeProfileName); + await eventListener.AssertMinimumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,1); + await eventListener.AssertMaximumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,50); + await eventListener.AssertRegEx(nameof(autoUpgradeProfileName), autoUpgradeProfileName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// The request should only proceed if an entity matches this string. + /// 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesDelete(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, string ifMatch, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a AutoUpgradeProfile + /// + /// The request should only proceed if an entity matches this string. + /// 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesDeleteViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesDelete_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.ContainerServiceFleet.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 AutoUpgradeProfilesDelete_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile 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 AutoUpgradeProfilesDelete_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string autoUpgradeProfileName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(autoUpgradeProfileName),autoUpgradeProfileName); + await eventListener.AssertMinimumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,1); + await eventListener.AssertMaximumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,50); + await eventListener.AssertRegEx(nameof(autoUpgradeProfileName), autoUpgradeProfileName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Get a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesGet(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a AutoUpgradeProfile + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesGetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a AutoUpgradeProfile + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var autoUpgradeProfileName = _match.Groups["autoUpgradeProfileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles/" + + autoUpgradeProfileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a AutoUpgradeProfile + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesGetWithResult(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles/" + + global::System.Uri.EscapeDataString(autoUpgradeProfileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesGetWithResult_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.ContainerServiceFleet.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 AutoUpgradeProfilesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 AutoUpgradeProfilesGet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet resource. + /// The name of the AutoUpgradeProfile 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 AutoUpgradeProfilesGet_Validate(string subscriptionId, string resourceGroupName, string fleetName, string autoUpgradeProfileName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(autoUpgradeProfileName),autoUpgradeProfileName); + await eventListener.AssertMinimumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,1); + await eventListener.AssertMaximumLength(nameof(autoUpgradeProfileName),autoUpgradeProfileName,50); + await eventListener.AssertRegEx(nameof(autoUpgradeProfileName), autoUpgradeProfileName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// List AutoUpgradeProfile resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesListByFleet(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List AutoUpgradeProfile resources by Fleet + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesListByFleetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AutoUpgradeProfilesListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List AutoUpgradeProfile resources by Fleet + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesListByFleetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/autoUpgradeProfiles$", 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.ContainerService/fleets/{fleetName}/autoUpgradeProfiles'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/autoUpgradeProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesListByFleetWithResult_Call (request, eventListener,sender); + } + } + + /// List AutoUpgradeProfile resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task AutoUpgradeProfilesListByFleetWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/autoUpgradeProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.AutoUpgradeProfilesListByFleetWithResult_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.ContainerServiceFleet.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 AutoUpgradeProfilesListByFleetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 AutoUpgradeProfilesListByFleet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 AutoUpgradeProfilesListByFleet_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// create a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 FleetMembersCreate(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a FleetMember + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 FleetMembersCreateViaIdentity(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a FleetMember + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetMembersCreateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the FleetMembersCreate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersCreateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, string ifNoneMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the FleetMembersCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, string ifNoneMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetMembersCreateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersCreateWithResult_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.ContainerServiceFleet.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 FleetMembersCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMembersCreate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The name of the Fleet resource. + /// The name of the Fleet member 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 FleetMembersCreate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string ifNoneMatch, string fleetName, string fleetMemberName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(ifNoneMatch),ifNoneMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(fleetMemberName),fleetMemberName); + await eventListener.AssertMinimumLength(nameof(fleetMemberName),fleetMemberName,1); + await eventListener.AssertMaximumLength(nameof(fleetMemberName),fleetMemberName,50); + await eventListener.AssertRegEx(nameof(fleetMemberName), fleetMemberName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersDelete(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a FleetMember + /// + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersDeleteViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetMembersDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the Fleet member 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 FleetMembersDelete_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string fleetMemberName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(fleetMemberName),fleetMemberName); + await eventListener.AssertMinimumLength(nameof(fleetMemberName),fleetMemberName,1); + await eventListener.AssertMaximumLength(nameof(fleetMemberName),fleetMemberName,50); + await eventListener.AssertRegEx(nameof(fleetMemberName), fleetMemberName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Get a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersGet(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a FleetMember + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersGetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a FleetMember + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersGetWithResult(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersGetWithResult_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.ContainerServiceFleet.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 FleetMembersGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMembersGet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet resource. + /// The name of the Fleet member 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 FleetMembersGet_Validate(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(fleetMemberName),fleetMemberName); + await eventListener.AssertMinimumLength(nameof(fleetMemberName),fleetMemberName,1); + await eventListener.AssertMaximumLength(nameof(fleetMemberName),fleetMemberName,50); + await eventListener.AssertRegEx(nameof(fleetMemberName), fleetMemberName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// List FleetMember resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersListByFleet(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FleetMember resources by Fleet + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersListByFleetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members$", 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.ContainerService/fleets/{fleetName}/members'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FleetMember resources by Fleet + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersListByFleetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members$", 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.ContainerService/fleets/{fleetName}/members'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersListByFleetWithResult_Call (request, eventListener,sender); + } + } + + /// List FleetMember resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersListByFleetWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersListByFleetWithResult_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.ContainerServiceFleet.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 FleetMembersListByFleetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMembersListByFleet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 FleetMembersListByFleet_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// update a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// 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.ContainerServiceFleet.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 FleetMembersUpdate(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FleetMember + /// + /// The request should only proceed if an entity matches this string. + /// 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.ContainerServiceFleet.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 FleetMembersUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FleetMember + /// + /// The request should only proceed if an entity matches this string. + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetMembersUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/members/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/members/{fleetMemberName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var fleetMemberName = _match.Groups["fleetMemberName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/members/" + + fleetMemberName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// Json string supplied to the FleetMembersUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetMembersUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// Json string supplied to the FleetMembersUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetMembersUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a FleetMember + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Fleet member resource. + /// The request should only proceed if an entity matches this string. + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetMembersUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string fleetMemberName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/members/" + + global::System.Uri.EscapeDataString(fleetMemberName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetMembersUpdateWithResult_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.ContainerServiceFleet.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 FleetMembersUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMembersUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the Fleet member 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 FleetMembersUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string fleetMemberName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(fleetMemberName),fleetMemberName); + await eventListener.AssertMinimumLength(nameof(fleetMemberName),fleetMemberName,1); + await eventListener.AssertMaximumLength(nameof(fleetMemberName),fleetMemberName,50); + await eventListener.AssertRegEx(nameof(fleetMemberName), fleetMemberName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// update a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 FleetUpdateStrategiesCreateOrUpdate(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FleetUpdateStrategy + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 FleetUpdateStrategiesCreateOrUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateStrategyName = _match.Groups["updateStrategyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies/" + + updateStrategyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FleetUpdateStrategy + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetUpdateStrategiesCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateStrategyName = _match.Groups["updateStrategyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies/" + + updateStrategyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the FleetUpdateStrategiesCreateOrUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, string ifMatch, string ifNoneMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the FleetUpdateStrategiesCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, string ifMatch, string ifNoneMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetUpdateStrategiesCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesCreateOrUpdateWithResult_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.ContainerServiceFleet.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 FleetUpdateStrategiesCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetUpdateStrategiesCreateOrUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy 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 FleetUpdateStrategiesCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string ifNoneMatch, string fleetName, string updateStrategyName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(ifNoneMatch),ifNoneMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateStrategyName),updateStrategyName); + await eventListener.AssertMinimumLength(nameof(updateStrategyName),updateStrategyName,1); + await eventListener.AssertMaximumLength(nameof(updateStrategyName),updateStrategyName,50); + await eventListener.AssertRegEx(nameof(updateStrategyName), updateStrategyName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy resource. + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesDelete(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a FleetUpdateStrategy + /// + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesDeleteViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateStrategyName = _match.Groups["updateStrategyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies/" + + updateStrategyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetUpdateStrategiesDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // declared final-state-via: azure-async-operation + var _finalUri = _response.GetFirstHeader(@"Azure-AsyncOperation"); + 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy 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 FleetUpdateStrategiesDelete_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string updateStrategyName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateStrategyName),updateStrategyName); + await eventListener.AssertMinimumLength(nameof(updateStrategyName),updateStrategyName,1); + await eventListener.AssertMaximumLength(nameof(updateStrategyName),updateStrategyName,50); + await eventListener.AssertRegEx(nameof(updateStrategyName), updateStrategyName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Get a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesGet(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a FleetUpdateStrategy + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesGetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateStrategyName = _match.Groups["updateStrategyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies/" + + updateStrategyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a FleetUpdateStrategy + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateStrategyName = _match.Groups["updateStrategyName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies/" + + updateStrategyName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a FleetUpdateStrategy + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesGetWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies/" + + global::System.Uri.EscapeDataString(updateStrategyName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesGetWithResult_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.ContainerServiceFleet.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 FleetUpdateStrategiesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetUpdateStrategiesGet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet resource. + /// The name of the UpdateStrategy 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 FleetUpdateStrategiesGet_Validate(string subscriptionId, string resourceGroupName, string fleetName, string updateStrategyName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateStrategyName),updateStrategyName); + await eventListener.AssertMinimumLength(nameof(updateStrategyName),updateStrategyName,1); + await eventListener.AssertMaximumLength(nameof(updateStrategyName),updateStrategyName,50); + await eventListener.AssertRegEx(nameof(updateStrategyName), updateStrategyName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// List FleetUpdateStrategy resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesListByFleet(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FleetUpdateStrategy resources by Fleet + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesListByFleetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies$", 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.ContainerService/fleets/{fleetName}/updateStrategies'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetUpdateStrategiesListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FleetUpdateStrategy resources by Fleet + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesListByFleetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateStrategies$", 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.ContainerService/fleets/{fleetName}/updateStrategies'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateStrategies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesListByFleetWithResult_Call (request, eventListener,sender); + } + } + + /// List FleetUpdateStrategy resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetUpdateStrategiesListByFleetWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateStrategies" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetUpdateStrategiesListByFleetWithResult_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.ContainerServiceFleet.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 FleetUpdateStrategiesListByFleetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetUpdateStrategiesListByFleet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 FleetUpdateStrategiesListByFleet_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// update a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 FleetsCreateOrUpdate(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Fleet. + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 FleetsCreateOrUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Fleet. + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the FleetsCreateOrUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, string ifNoneMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the FleetsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, string ifNoneMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsCreateOrUpdateWithResult_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.ContainerServiceFleet.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 FleetsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetsCreateOrUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The name of the Fleet 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 FleetsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string ifNoneMatch, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(ifNoneMatch),ifNoneMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsDelete(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a Fleet + /// + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsDeleteViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet 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 FleetsDelete_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Gets a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsGet(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets a Fleet. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsGetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Gets a Fleet. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Gets a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsGetWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsGetWithResult_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.ContainerServiceFleet.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 FleetsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetsGet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 FleetsGet_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Lists fleets in the specified subscription and 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListByResourceGroup(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists fleets in the specified subscription and 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListByResourceGroupViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets$", 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.ContainerService/fleets'"); + } + + // 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.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists fleets in the specified subscription and resource group. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListByResourceGroupViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets$", 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.ContainerService/fleets'"); + } + + // 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.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// Lists fleets in the specified subscription and 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListByResourceGroupWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsListByResourceGroupWithResult_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.ContainerServiceFleet.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 FleetsListByResourceGroupWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetsListByResourceGroup_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + } + } + + /// Lists fleets in the specified 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists fleets in the specified subscription. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListBySubscriptionViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.ContainerService/fleets$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/fleets'"); + } + + // 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.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists fleets in the specified subscription. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.ContainerService/fleets$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/fleets'"); + } + + // 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.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// Lists fleets in the specified 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.ContainerService/fleets" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsListBySubscriptionWithResult_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.ContainerServiceFleet.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 FleetsListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetsListBySubscription_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + } + } + + /// Lists the user credentials of a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListCredentials(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/listCredentials" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsListCredentials_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists the user credentials of a Fleet. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListCredentialsViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/listCredentials" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsListCredentials_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists the user credentials of a Fleet. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListCredentialsViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/listCredentials" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsListCredentialsWithResult_Call (request, eventListener,sender); + } + } + + /// Lists the user credentials of a Fleet. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsListCredentialsWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/listCredentials" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsListCredentialsWithResult_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.ContainerServiceFleet.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 FleetsListCredentialsWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetCredentialResults.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetsListCredentials_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetCredentialResults.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 FleetsListCredentials_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Update a Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// 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.ContainerServiceFleet.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 FleetsUpdate(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a Fleet + /// + /// The request should only proceed if an entity matches this string. + /// 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.ContainerServiceFleet.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 FleetsUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a Fleet + /// + /// The request should only proceed if an entity matches this string. + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// Json string supplied to the FleetsUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FleetsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// Json string supplied to the FleetsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FleetsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The request should only proceed if an entity matches this string. + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetsUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FleetsUpdateWithResult_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.ContainerServiceFleet.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 FleetsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetsUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet 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 FleetsUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Get a Gate + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesGet(string subscriptionId, string resourceGroupName, string fleetName, string gateName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates/" + + global::System.Uri.EscapeDataString(gateName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Gate + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesGetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/gates/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/gates/{gateName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var gateName = _match.Groups["gateName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/gates/" + + gateName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a Gate + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/gates/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/gates/{gateName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var gateName = _match.Groups["gateName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/gates/" + + gateName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a Gate + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesGetWithResult(string subscriptionId, string resourceGroupName, string fleetName, string gateName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates/" + + global::System.Uri.EscapeDataString(gateName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesGetWithResult_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.ContainerServiceFleet.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 GatesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Gate.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 GatesGet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Gate.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// 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 GatesGet_Validate(string subscriptionId, string resourceGroupName, string fleetName, string gateName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(gateName),gateName); + await eventListener.AssertMinimumLength(nameof(gateName),gateName,36); + await eventListener.AssertMaximumLength(nameof(gateName),gateName,36); + await eventListener.AssertRegEx(nameof(gateName), gateName, @"^[0-9a-f]{8}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{12}$"); + } + } + + /// List Gate resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesListByFleet(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List Gate resources by Fleet + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesListByFleetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/gates$", 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.ContainerService/fleets/{fleetName}/gates'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/gates" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List Gate resources by Fleet + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesListByFleetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/gates$", 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.ContainerService/fleets/{fleetName}/gates'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/gates" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesListByFleetWithResult_Call (request, eventListener,sender); + } + } + + /// List Gate resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesListByFleetWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesListByFleetWithResult_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.ContainerServiceFleet.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 GatesListByFleetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 GatesListByFleet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 GatesListByFleet_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// update a Gate + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 GatesUpdate(string subscriptionId, string resourceGroupName, string fleetName, string gateName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates/" + + global::System.Uri.EscapeDataString(gateName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Gate + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 GatesUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/gates/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/gates/{gateName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var gateName = _match.Groups["gateName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/gates/" + + gateName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Gate + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 GatesUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/gates/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/gates/{gateName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var gateName = _match.Groups["gateName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/gates/" + + gateName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Gate + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the GatesUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string gateName, string ifMatch, string ifNoneMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates/" + + global::System.Uri.EscapeDataString(gateName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.GatesUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a Gate + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the GatesUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task GatesUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string gateName, string ifMatch, string ifNoneMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates/" + + global::System.Uri.EscapeDataString(gateName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Gate + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 GatesUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string gateName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/gates/" + + global::System.Uri.EscapeDataString(gateName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.GatesUpdateWithResult_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.ContainerServiceFleet.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 GatesUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Gate.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 GatesUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Gate.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The name of the Fleet resource. + /// The name of the Gate resource, a GUID. + /// 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 GatesUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string ifNoneMatch, string fleetName, string gateName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(ifNoneMatch),ifNoneMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(gateName),gateName); + await eventListener.AssertMinimumLength(nameof(gateName),gateName,36); + await eventListener.AssertMaximumLength(nameof(gateName),gateName,36); + await eventListener.AssertRegEx(nameof(gateName), gateName, @"^[0-9a-f]{8}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{12}$"); + 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.ContainerService/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.ISendAsync pipeline to 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.ContainerService/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.ContainerService/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.ContainerService/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.ISendAsync pipeline to 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.ContainerService/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.ContainerService/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.ContainerService/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.ISendAsync pipeline to 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.ContainerService/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// update a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 UpdateRunsCreateOrUpdate(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a UpdateRun + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// 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.ContainerServiceFleet.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 UpdateRunsCreateOrUpdateViaIdentity(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a UpdateRun + /// + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 UpdateRunsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the UpdateRunsCreateOrUpdate 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, string ifNoneMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Json string supplied to the UpdateRunsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, string ifNoneMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 UpdateRunsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, string ifNoneMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + if (null != ifNoneMatch) + { + request.Headers.Add("If-None-Match",ifNoneMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsCreateOrUpdateWithResult_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.ContainerServiceFleet.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 UpdateRunsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunsCreateOrUpdate_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The request should only proceed if no entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateRun 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 UpdateRunsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string ifNoneMatch, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(ifNoneMatch),ifNoneMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateRunName),updateRunName); + await eventListener.AssertMinimumLength(nameof(updateRunName),updateRunName,1); + await eventListener.AssertMaximumLength(nameof(updateRunName),updateRunName,50); + await eventListener.AssertRegEx(nameof(updateRunName), updateRunName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsDelete(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete a UpdateRun + /// + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsDeleteViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsDelete_Call (request, onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 UpdateRunsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateRun 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 UpdateRunsDelete_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateRunName),updateRunName); + await eventListener.AssertMinimumLength(nameof(updateRunName),updateRunName,1); + await eventListener.AssertMaximumLength(nameof(updateRunName),updateRunName,50); + await eventListener.AssertRegEx(nameof(updateRunName), updateRunName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Get a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsGet(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a UpdateRun + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsGetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a UpdateRun + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a UpdateRun + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsGetWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsGetWithResult_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.ContainerServiceFleet.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 UpdateRunsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunsGet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet resource. + /// The name of the UpdateRun 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 UpdateRunsGet_Validate(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateRunName),updateRunName); + await eventListener.AssertMinimumLength(nameof(updateRunName),updateRunName,1); + await eventListener.AssertMaximumLength(nameof(updateRunName),updateRunName,50); + await eventListener.AssertRegEx(nameof(updateRunName), updateRunName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// List UpdateRun resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsListByFleet(string subscriptionId, string resourceGroupName, string fleetName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List UpdateRun resources by Fleet + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsListByFleetViaIdentity(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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns$", 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.ContainerService/fleets/{fleetName}/updateRuns'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsListByFleet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List UpdateRun resources by Fleet + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsListByFleetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns$", 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.ContainerService/fleets/{fleetName}/updateRuns'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsListByFleetWithResult_Call (request, eventListener,sender); + } + } + + /// List UpdateRun resources by Fleet + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsListByFleetWithResult(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsListByFleetWithResult_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.ContainerServiceFleet.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 UpdateRunsListByFleetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunsListByFleet_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The name of the Fleet 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 UpdateRunsListByFleet_Validate(string subscriptionId, string resourceGroupName, string fleetName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// The content of the action 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.ContainerServiceFleet.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 UpdateRunsSkip(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/skip" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsSkip_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// The request should only proceed if an entity matches this string. + /// The content of the action 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.ContainerServiceFleet.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 UpdateRunsSkipViaIdentity(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "/skip" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsSkip_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// The request should only proceed if an entity matches this string. + /// The content of the action request + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 UpdateRunsSkipViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "/skip" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsSkipWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// Json string supplied to the UpdateRunsSkip 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.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsSkipViaJsonString(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, 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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/skip" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsSkip_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// Json string supplied to the UpdateRunsSkip operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsSkipViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/skip" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsSkipWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// The content of the action request + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 UpdateRunsSkipWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/skip" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsSkipWithResult_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.ContainerServiceFleet.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 UpdateRunsSkipWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunsSkip_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The content of the action 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 UpdateRunsSkip_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties body, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateRunName),updateRunName); + await eventListener.AssertMinimumLength(nameof(updateRunName),updateRunName,1); + await eventListener.AssertMaximumLength(nameof(updateRunName),updateRunName,50); + await eventListener.AssertRegEx(nameof(updateRunName), updateRunName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Starts an UpdateRun. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStart(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/start" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsStart_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Starts an UpdateRun. + /// + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStartViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "/start" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsStart_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Starts an UpdateRun. + /// + /// The request should only proceed if an entity matches this string. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStartViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "/start" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsStartWithResult_Call (request, eventListener,sender); + } + } + + /// Starts an UpdateRun. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStartWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/start" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsStartWithResult_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.ContainerServiceFleet.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 UpdateRunsStartWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunsStart_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateRun 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 UpdateRunsStart_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateRunName),updateRunName); + await eventListener.AssertMinimumLength(nameof(updateRunName),updateRunName,1); + await eventListener.AssertMaximumLength(nameof(updateRunName),updateRunName,50); + await eventListener.AssertRegEx(nameof(updateRunName), updateRunName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + + /// Stops an UpdateRun. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStop(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/stop" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsStop_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Stops an UpdateRun. + /// + /// The request should only proceed if an entity matches this string. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStopViaIdentity(global::System.String viaIdentity, string ifMatch, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "/stop" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UpdateRunsStop_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Stops an UpdateRun. + /// + /// The request should only proceed if an entity matches this string. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStopViaIdentityWithResult(global::System.String viaIdentity, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ContainerService/fleets/(?[^/]+)/updateRuns/(?[^/]+)$", 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.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fleetName = _match.Groups["fleetName"].Value; + var updateRunName = _match.Groups["updateRunName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ContainerService/fleets/" + + fleetName + + "/updateRuns/" + + updateRunName + + "/stop" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsStopWithResult_Call (request, eventListener,sender); + } + } + + /// Stops an UpdateRun. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Fleet resource. + /// The name of the UpdateRun resource. + /// The request should only proceed if an entity matches this string. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task UpdateRunsStopWithResult(string subscriptionId, string resourceGroupName, string fleetName, string updateRunName, string ifMatch, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + var apiVersion = @"2025-04-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/Microsoft.ContainerService/fleets/" + + global::System.Uri.EscapeDataString(fleetName) + + "/updateRuns/" + + global::System.Uri.EscapeDataString(updateRunName) + + "/stop" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // add headers parameters + if (null != ifMatch) + { + request.Headers.Add("If-Match",ifMatch); + } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.UpdateRunsStopWithResult_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.ContainerServiceFleet.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 UpdateRunsStopWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunsStop_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.ContainerServiceFleet.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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. + /// The request should only proceed if an entity matches this string. + /// The name of the Fleet resource. + /// The name of the UpdateRun 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 UpdateRunsStop_Validate(string subscriptionId, string resourceGroupName, string ifMatch, string fleetName, string updateRunName, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName), resourceGroupName, @"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(ifMatch),ifMatch); + await eventListener.AssertNotNull(nameof(fleetName),fleetName); + await eventListener.AssertMinimumLength(nameof(fleetName),fleetName,1); + await eventListener.AssertMaximumLength(nameof(fleetName),fleetName,63); + await eventListener.AssertRegEx(nameof(fleetName), fleetName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + await eventListener.AssertNotNull(nameof(updateRunName),updateRunName); + await eventListener.AssertMinimumLength(nameof(updateRunName),updateRunName,1); + await eventListener.AssertMaximumLength(nameof(updateRunName),updateRunName,50); + await eventListener.AssertRegEx(nameof(updateRunName), updateRunName, @"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.PowerShell.cs new file mode 100644 index 00000000000..977bcc44dd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Agent profile for the Fleet hub. + [System.ComponentModel.TypeConverter(typeof(AgentProfileTypeConverter))] + public partial class AgentProfile + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AgentProfile(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).SubnetId = (string) content.GetValueForProperty("SubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).SubnetId, global::System.Convert.ToString); + } + if (content.Contains("VMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).VMSize = (string) content.GetValueForProperty("VMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).VMSize, 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 AgentProfile(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).SubnetId = (string) content.GetValueForProperty("SubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).SubnetId, global::System.Convert.ToString); + } + if (content.Contains("VMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).VMSize = (string) content.GetValueForProperty("VMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)this).VMSize, 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.ContainerServiceFleet.Models.IAgentProfile DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AgentProfile(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AgentProfile(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// Agent profile for the Fleet hub. + [System.ComponentModel.TypeConverter(typeof(AgentProfileTypeConverter))] + public partial interface IAgentProfile + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.TypeConverter.cs new file mode 100644 index 00000000000..8e7a950ecff --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AgentProfileTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAgentProfile ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AgentProfile.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AgentProfile.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AgentProfile.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AgentProfile.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.cs new file mode 100644 index 00000000000..b02fd3b3dbe --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Agent profile for the Fleet hub. + public partial class AgentProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal + { + + /// Backing field for property. + private string _subnetId; + + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string SubnetId { get => this._subnetId; set => this._subnetId = value; } + + /// Backing field for property. + private string _vMSize; + + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string VMSize { get => this._vMSize; set => this._vMSize = value; } + + /// Creates an new instance. + public AgentProfile() + { + + } + } + /// Agent profile for the Fleet hub. + public partial interface IAgentProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string SubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The virtual machine size of the Fleet hub.", + SerializedName = @"vmSize", + PossibleTypes = new [] { typeof(string) })] + string VMSize { get; set; } + + } + /// Agent profile for the Fleet hub. + internal partial interface IAgentProfileInternal + + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + string SubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + string VMSize { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.json.cs new file mode 100644 index 00000000000..7de2cf4aa65 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AgentProfile.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Agent profile for the Fleet hub. + public partial class AgentProfile + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AgentProfile(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_subnetId = If( json?.PropertyT("subnetId"), out var __jsonSubnetId) ? (string)__jsonSubnetId : (string)_subnetId;} + {_vMSize = If( json?.PropertyT("vmSize"), out var __jsonVMSize) ? (string)__jsonVMSize : (string)_vMSize;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AgentProfile(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._subnetId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._subnetId.ToString()) : null, "subnetId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._vMSize)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._vMSize.ToString()) : null, "vmSize" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..5a12db90a27 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..7ab11005f7c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..ad4d70e9c9c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..42f92121717 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Any.json.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAny. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.PowerShell.cs new file mode 100644 index 00000000000..633c60db19f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Access profile for the Fleet hub API server. + [System.ComponentModel.TypeConverter(typeof(ApiServerAccessProfileTypeConverter))] + public partial class ApiServerAccessProfile + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ApiServerAccessProfile(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("EnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnablePrivateCluster = (bool?) content.GetValueForProperty("EnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnableVnetIntegration = (bool?) content.GetValueForProperty("EnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).SubnetId = (string) content.GetValueForProperty("SubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).SubnetId, 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 ApiServerAccessProfile(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("EnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnablePrivateCluster = (bool?) content.GetValueForProperty("EnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnableVnetIntegration = (bool?) content.GetValueForProperty("EnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).EnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("SubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).SubnetId = (string) content.GetValueForProperty("SubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)this).SubnetId, 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.ContainerServiceFleet.Models.IApiServerAccessProfile DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ApiServerAccessProfile(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ApiServerAccessProfile(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// Access profile for the Fleet hub API server. + [System.ComponentModel.TypeConverter(typeof(ApiServerAccessProfileTypeConverter))] + public partial interface IApiServerAccessProfile + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.TypeConverter.cs new file mode 100644 index 00000000000..9753089447d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ApiServerAccessProfileTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IApiServerAccessProfile ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ApiServerAccessProfile.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ApiServerAccessProfile.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ApiServerAccessProfile.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.cs new file mode 100644 index 00000000000..8ea5d7f74d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Access profile for the Fleet hub API server. + public partial class ApiServerAccessProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal + { + + /// Backing field for property. + private bool? _enablePrivateCluster; + + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public bool? EnablePrivateCluster { get => this._enablePrivateCluster; set => this._enablePrivateCluster = value; } + + /// Backing field for property. + private bool? _enableVnetIntegration; + + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public bool? EnableVnetIntegration { get => this._enableVnetIntegration; set => this._enableVnetIntegration = value; } + + /// Backing field for property. + private string _subnetId; + + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string SubnetId { get => this._subnetId; set => this._subnetId = value; } + + /// Creates an new instance. + public ApiServerAccessProfile() + { + + } + } + /// Access profile for the Fleet hub API server. + public partial interface IApiServerAccessProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to create the Fleet hub as a private cluster or not.", + SerializedName = @"enablePrivateCluster", + PossibleTypes = new [] { typeof(bool) })] + bool? EnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to enable apiserver vnet integration for the Fleet hub or not.", + SerializedName = @"enableVnetIntegration", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string SubnetId { get; set; } + + } + /// Access profile for the Fleet hub API server. + internal partial interface IApiServerAccessProfileInternal + + { + /// Whether to create the Fleet hub as a private cluster or not. + bool? EnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + bool? EnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + string SubnetId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.json.cs new file mode 100644 index 00000000000..21f479fae21 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ApiServerAccessProfile.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Access profile for the Fleet hub API server. + public partial class ApiServerAccessProfile + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ApiServerAccessProfile(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_enablePrivateCluster = If( json?.PropertyT("enablePrivateCluster"), out var __jsonEnablePrivateCluster) ? (bool?)__jsonEnablePrivateCluster : _enablePrivateCluster;} + {_enableVnetIntegration = If( json?.PropertyT("enableVnetIntegration"), out var __jsonEnableVnetIntegration) ? (bool?)__jsonEnableVnetIntegration : _enableVnetIntegration;} + {_subnetId = If( json?.PropertyT("subnetId"), out var __jsonSubnetId) ? (string)__jsonSubnetId : (string)_subnetId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ApiServerAccessProfile(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._enablePrivateCluster ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonBoolean((bool)this._enablePrivateCluster) : null, "enablePrivateCluster" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._enableVnetIntegration ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonBoolean((bool)this._enableVnetIntegration) : null, "enableVnetIntegration" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._subnetId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._subnetId.ToString()) : null, "subnetId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.PowerShell.cs new file mode 100644 index 00000000000..098054107bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The node image upgrade to be applied to the target clusters in auto upgrade. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeNodeImageSelectionTypeConverter))] + public partial class AutoUpgradeNodeImageSelection + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AutoUpgradeNodeImageSelection(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.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal)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 AutoUpgradeNodeImageSelection(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.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AutoUpgradeNodeImageSelection(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AutoUpgradeNodeImageSelection(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 node image upgrade to be applied to the target clusters in auto upgrade. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeNodeImageSelectionTypeConverter))] + public partial interface IAutoUpgradeNodeImageSelection + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.TypeConverter.cs new file mode 100644 index 00000000000..a0ea3801954 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AutoUpgradeNodeImageSelectionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AutoUpgradeNodeImageSelection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AutoUpgradeNodeImageSelection.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AutoUpgradeNodeImageSelection.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.cs new file mode 100644 index 00000000000..39d24e07db1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node image upgrade to be applied to the target clusters in auto upgrade. + public partial class AutoUpgradeNodeImageSelection : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal + { + + /// Backing field for property. + private string _type; + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public AutoUpgradeNodeImageSelection() + { + + } + } + /// The node image upgrade to be applied to the target clusters in auto upgrade. + public partial interface IAutoUpgradeNodeImageSelection : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + string Type { get; set; } + + } + /// The node image upgrade to be applied to the target clusters in auto upgrade. + internal partial interface IAutoUpgradeNodeImageSelectionInternal + + { + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.json.cs new file mode 100644 index 00000000000..b8206bb4992 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeNodeImageSelection.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node image upgrade to be applied to the target clusters in auto upgrade. + public partial class AutoUpgradeNodeImageSelection + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AutoUpgradeNodeImageSelection(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AutoUpgradeNodeImageSelection(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.PowerShell.cs new file mode 100644 index 00000000000..1dde0b86de8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The AutoUpgradeProfile resource. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileTypeConverter))] + public partial class AutoUpgradeProfile + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AutoUpgradeProfile(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.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfilePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("Channel")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Channel = (string) content.GetValueForProperty("Channel",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Channel, global::System.Convert.ToString); + } + if (content.Contains("Disabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Disabled = (bool?) content.GetValueForProperty("Disabled",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Disabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).TargetKubernetesVersion = (string) content.GetValueForProperty("TargetKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).TargetKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("LongTermSupport")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LongTermSupport = (bool?) content.GetValueForProperty("LongTermSupport",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LongTermSupport, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("StatusLastTriggerError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastTriggerError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastTriggeredAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggeredAt = (global::System.DateTime?) content.GetValueForProperty("StatusLastTriggeredAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggeredAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusLastTriggerStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerStatus = (string) content.GetValueForProperty("StatusLastTriggerStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerStatus, global::System.Convert.ToString); + } + if (content.Contains("StatusLastTriggerUpgradeVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerUpgradeVersion = (System.Collections.Generic.List) content.GetValueForProperty("StatusLastTriggerUpgradeVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerUpgradeVersion, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("LastTriggerErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorCode = (string) content.GetValueForProperty("LastTriggerErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorMessage = (string) content.GetValueForProperty("LastTriggerErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorTarget = (string) content.GetValueForProperty("LastTriggerErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastTriggerErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AutoUpgradeProfile(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.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfilePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("Channel")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Channel = (string) content.GetValueForProperty("Channel",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Channel, global::System.Convert.ToString); + } + if (content.Contains("Disabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Disabled = (bool?) content.GetValueForProperty("Disabled",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).Disabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).TargetKubernetesVersion = (string) content.GetValueForProperty("TargetKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).TargetKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("LongTermSupport")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LongTermSupport = (bool?) content.GetValueForProperty("LongTermSupport",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LongTermSupport, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("StatusLastTriggerError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastTriggerError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastTriggeredAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggeredAt = (global::System.DateTime?) content.GetValueForProperty("StatusLastTriggeredAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggeredAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusLastTriggerStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerStatus = (string) content.GetValueForProperty("StatusLastTriggerStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerStatus, global::System.Convert.ToString); + } + if (content.Contains("StatusLastTriggerUpgradeVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerUpgradeVersion = (System.Collections.Generic.List) content.GetValueForProperty("StatusLastTriggerUpgradeVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).StatusLastTriggerUpgradeVersion, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("LastTriggerErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorCode = (string) content.GetValueForProperty("LastTriggerErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorMessage = (string) content.GetValueForProperty("LastTriggerErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorTarget = (string) content.GetValueForProperty("LastTriggerErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastTriggerErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal)this).LastTriggerErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.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.ContainerServiceFleet.Models.IAutoUpgradeProfile DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AutoUpgradeProfile(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AutoUpgradeProfile(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 AutoUpgradeProfile resource. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileTypeConverter))] + public partial interface IAutoUpgradeProfile + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.TypeConverter.cs new file mode 100644 index 00000000000..b626849cc2a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AutoUpgradeProfileTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAutoUpgradeProfile ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AutoUpgradeProfile.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AutoUpgradeProfile.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AutoUpgradeProfile.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.cs new file mode 100644 index 00000000000..99b5801e312 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.cs @@ -0,0 +1,559 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The AutoUpgradeProfile resource. + public partial class AutoUpgradeProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(); + + /// Configures how auto-upgrade will be run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Channel { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).Channel; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).Channel = value ?? null; } + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + /// If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + /// This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + /// By default, this is set to False. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? Disabled { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).Disabled; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).Disabled = value ?? default(bool); } + + /// Backing field for property. + private string _eTag; + + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorAdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorCode; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastTriggerErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorDetail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorMessage; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorTarget; } + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. + /// If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + /// (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + /// By default, this is set to False. + /// For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? LongTermSupport { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LongTermSupport; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LongTermSupport = value ?? default(bool); } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for LastTriggerErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.LastTriggerErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorAdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorAdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastTriggerErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.LastTriggerErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorCode = value ?? null; } + + /// Internal Acessors for LastTriggerErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.LastTriggerErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorDetail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastTriggerErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.LastTriggerErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorMessage = value ?? null; } + + /// Internal Acessors for LastTriggerErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.LastTriggerErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorTarget; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).LastTriggerErrorTarget = value ?? null; } + + /// Internal Acessors for NodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.NodeImageSelection { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).NodeImageSelection; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).NodeImageSelection = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatus = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastTriggerError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.StatusLastTriggerError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerError = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastTriggerStatus + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.StatusLastTriggerStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerStatus = value ?? null; } + + /// Internal Acessors for StatusLastTriggerUpgradeVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.StatusLastTriggerUpgradeVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerUpgradeVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerUpgradeVersion = value ?? null /* arrayOf */; } + + /// Internal Acessors for StatusLastTriggeredAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileInternal.StatusLastTriggeredAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggeredAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggeredAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; } + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string NodeImageSelectionType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).NodeImageSelectionType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).NodeImageSelectionType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileProperties()); set => this._property = value; } + + /// The provisioning state of the AutoUpgradeProfile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// The status of the last AutoUpgrade trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusLastTriggerStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerStatus; } + + /// The target Kubernetes version or node image versions of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StatusLastTriggerUpgradeVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggerUpgradeVersion; } + + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusLastTriggeredAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).AutoUpgradeProfileStatusLastTriggeredAt; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". + /// By default, this is empty. + /// If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string TargetKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).TargetKubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).TargetKubernetesVersion = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; } + + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateStrategyId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).UpdateStrategyId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)Property).UpdateStrategyId = value ?? null; } + + /// Creates an new instance. + public AutoUpgradeProfile() + { + + } + + /// 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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// The AutoUpgradeProfile resource. + public partial interface IAutoUpgradeProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource + { + /// Configures how auto-upgrade will be run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + string Channel { get; set; } + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + /// If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + /// This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + /// By default, this is set to False. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(bool) })] + bool? Disabled { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastTriggerErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorTarget { get; } + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. + /// If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + /// (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + /// By default, this is set to False. + /// For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. + If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + By default, this is set to False. + For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(bool) })] + bool? LongTermSupport { get; set; } + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + string NodeImageSelectionType { get; set; } + /// The provisioning state of the AutoUpgradeProfile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the AutoUpgradeProfile resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The status of the last AutoUpgrade trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last AutoUpgrade trigger.", + SerializedName = @"lastTriggerStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed")] + string StatusLastTriggerStatus { get; } + /// The target Kubernetes version or node image versions of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The target Kubernetes version or node image versions of the last trigger.", + SerializedName = @"lastTriggerUpgradeVersions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List StatusLastTriggerUpgradeVersion { get; } + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions.", + SerializedName = @"lastTriggeredAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusLastTriggeredAt { get; } + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". + /// By default, this is empty. + /// If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". + By default, this is empty. + If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string TargetKubernetesVersion { get; set; } + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + string UpdateStrategyId { get; set; } + + } + /// The AutoUpgradeProfile resource. + internal partial interface IAutoUpgradeProfileInternal : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResourceInternal + { + /// Configures how auto-upgrade will be run. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + string Channel { get; set; } + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + /// If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + /// This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + /// By default, this is set to False. + /// + bool? Disabled { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + string ETag { get; set; } + /// The error additional info. + System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get; set; } + /// The error code. + string LastTriggerErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastTriggerErrorDetail { get; set; } + /// The error message. + string LastTriggerErrorMessage { get; set; } + /// The error target. + string LastTriggerErrorTarget { get; set; } + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. + /// If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + /// (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + /// By default, this is set to False. + /// For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + bool? LongTermSupport { get; set; } + /// The node image upgrade to be applied to the target clusters in auto upgrade. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection NodeImageSelection { get; set; } + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + string NodeImageSelectionType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties Property { get; set; } + /// The provisioning state of the AutoUpgradeProfile resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// The status of the auto upgrade profile. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus Status { get; set; } + /// The error details of the last trigger. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusLastTriggerError { get; set; } + /// The status of the last AutoUpgrade trigger. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed")] + string StatusLastTriggerStatus { get; set; } + /// The target Kubernetes version or node image versions of the last trigger. + System.Collections.Generic.List StatusLastTriggerUpgradeVersion { get; set; } + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + global::System.DateTime? StatusLastTriggeredAt { get; set; } + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". + /// By default, this is empty. + /// If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + string TargetKubernetesVersion { get; set; } + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + string UpdateStrategyId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.json.cs new file mode 100644 index 00000000000..a6033a5c3a9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfile.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The AutoUpgradeProfile resource. + public partial class AutoUpgradeProfile + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AutoUpgradeProfile(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileProperties.FromJson(__jsonProperties) : _property;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)_eTag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AutoUpgradeProfile(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.PowerShell.cs new file mode 100644 index 00000000000..c844d67312d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The response of a AutoUpgradeProfile list operation. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileListResultTypeConverter))] + public partial class AutoUpgradeProfileListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AutoUpgradeProfileListResult(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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)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 AutoUpgradeProfileListResult(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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal)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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AutoUpgradeProfileListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AutoUpgradeProfileListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 AutoUpgradeProfile list operation. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileListResultTypeConverter))] + public partial interface IAutoUpgradeProfileListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.TypeConverter.cs new file mode 100644 index 00000000000..051d21c043a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AutoUpgradeProfileListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AutoUpgradeProfileListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AutoUpgradeProfileListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AutoUpgradeProfileListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.cs new file mode 100644 index 00000000000..915fdbd5f23 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a AutoUpgradeProfile list operation. + public partial class AutoUpgradeProfileListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The AutoUpgradeProfile items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public AutoUpgradeProfileListResult() + { + + } + } + /// The response of a AutoUpgradeProfile list operation. + public partial interface IAutoUpgradeProfileListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 AutoUpgradeProfile items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The AutoUpgradeProfile items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a AutoUpgradeProfile list operation. + internal partial interface IAutoUpgradeProfileListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The AutoUpgradeProfile items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.json.cs new file mode 100644 index 00000000000..74530c7c416 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a AutoUpgradeProfile list operation. + public partial class AutoUpgradeProfileListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AutoUpgradeProfileListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile.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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AutoUpgradeProfileListResult(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..a774fe51ae9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.PowerShell.cs @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersTypeConverter))] + public partial class AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("IfMatch")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal)this).IfMatch = (string) content.GetValueForProperty("IfMatch",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal)this).IfMatch, 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 AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("IfMatch")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal)this).IfMatch = (string) content.GetValueForProperty("IfMatch",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal)this).IfMatch, 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.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders(content); + } + + /// + /// Creates a new instance of , deserializing + /// the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersTypeConverter))] + public partial interface IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..7616cddf495 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if + /// there is 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.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..7c516d03080 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _ifMatch; + + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// + /// Creates an new instance. + /// + public AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("If-Match", out var __ifMatchHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal)this).IfMatch = System.Linq.Enumerable.FirstOrDefault(__ifMatchHeader0) is string __headerIfMatchHeader0 ? __headerIfMatchHeader0 : (string)null; + } + } + } + public partial interface IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + string IfMatch { get; set; } + + } + internal partial interface IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeadersInternal + + { + string IfMatch { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..48565c78267 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AutoUpgradeProfileOperationsGenerateUpdateRunAcceptedResponseHeaders(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.PowerShell.cs new file mode 100644 index 00000000000..82d40ccb8b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.PowerShell.cs @@ -0,0 +1,300 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The properties of the AutoUpgradeProfile. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfilePropertiesTypeConverter))] + public partial class AutoUpgradeProfileProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AutoUpgradeProfileProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("AutoUpgradeProfileStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus) content.GetValueForProperty("AutoUpgradeProfileStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("Channel")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Channel = (string) content.GetValueForProperty("Channel",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Channel, global::System.Convert.ToString); + } + if (content.Contains("Disabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Disabled = (bool?) content.GetValueForProperty("Disabled",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Disabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).TargetKubernetesVersion = (string) content.GetValueForProperty("TargetKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).TargetKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("LongTermSupport")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LongTermSupport = (bool?) content.GetValueForProperty("LongTermSupport",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LongTermSupport, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggerError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggerError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggeredAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggeredAt = (global::System.DateTime?) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggeredAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggeredAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggerStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerStatus = (string) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggerStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerStatus, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggerUpgradeVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerUpgradeVersion = (System.Collections.Generic.List) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggerUpgradeVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerUpgradeVersion, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("LastTriggerErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorCode = (string) content.GetValueForProperty("LastTriggerErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorMessage = (string) content.GetValueForProperty("LastTriggerErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorTarget = (string) content.GetValueForProperty("LastTriggerErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastTriggerErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AutoUpgradeProfileProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("AutoUpgradeProfileStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus) content.GetValueForProperty("AutoUpgradeProfileStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("Channel")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Channel = (string) content.GetValueForProperty("Channel",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Channel, global::System.Convert.ToString); + } + if (content.Contains("Disabled")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Disabled = (bool?) content.GetValueForProperty("Disabled",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).Disabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("TargetKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).TargetKubernetesVersion = (string) content.GetValueForProperty("TargetKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).TargetKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("LongTermSupport")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LongTermSupport = (bool?) content.GetValueForProperty("LongTermSupport",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LongTermSupport, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggerError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggerError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggeredAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggeredAt = (global::System.DateTime?) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggeredAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggeredAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggerStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerStatus = (string) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggerStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerStatus, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileStatusLastTriggerUpgradeVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerUpgradeVersion = (System.Collections.Generic.List) content.GetValueForProperty("AutoUpgradeProfileStatusLastTriggerUpgradeVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).AutoUpgradeProfileStatusLastTriggerUpgradeVersion, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("LastTriggerErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorCode = (string) content.GetValueForProperty("LastTriggerErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorMessage = (string) content.GetValueForProperty("LastTriggerErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorTarget = (string) content.GetValueForProperty("LastTriggerErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastTriggerErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal)this).LastTriggerErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.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.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AutoUpgradeProfileProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AutoUpgradeProfileProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 properties of the AutoUpgradeProfile. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfilePropertiesTypeConverter))] + public partial interface IAutoUpgradeProfileProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.TypeConverter.cs new file mode 100644 index 00000000000..e34b61d428f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AutoUpgradeProfilePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AutoUpgradeProfileProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AutoUpgradeProfileProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AutoUpgradeProfileProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.cs new file mode 100644 index 00000000000..3cead309a1d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.cs @@ -0,0 +1,445 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the AutoUpgradeProfile. + public partial class AutoUpgradeProfileProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus _autoUpgradeProfileStatus; + + /// The status of the auto upgrade profile. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus AutoUpgradeProfileStatus { get => (this._autoUpgradeProfileStatus = this._autoUpgradeProfileStatus ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatus()); set => this._autoUpgradeProfileStatus = value; } + + /// The status of the last AutoUpgrade trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AutoUpgradeProfileStatusLastTriggerStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerStatus; } + + /// The target Kubernetes version or node image versions of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AutoUpgradeProfileStatusLastTriggerUpgradeVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerUpgradeVersion; } + + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? AutoUpgradeProfileStatusLastTriggeredAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggeredAt; } + + /// Backing field for property. + private string _channel; + + /// Configures how auto-upgrade will be run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Channel { get => this._channel; set => this._channel = value; } + + /// Backing field for property. + private bool? _disabled; + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + /// If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + /// This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + /// By default, this is set to False. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public bool? Disabled { get => this._disabled; set => this._disabled = value; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorAdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorCode; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastTriggerErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorDetail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorMessage; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorTarget; } + + /// Backing field for property. + private bool? _longTermSupport; + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. + /// If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + /// (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + /// By default, this is set to False. + /// For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public bool? LongTermSupport { get => this._longTermSupport; set => this._longTermSupport = value; } + + /// Internal Acessors for AutoUpgradeProfileStatus + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.AutoUpgradeProfileStatus { get => (this._autoUpgradeProfileStatus = this._autoUpgradeProfileStatus ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatus()); set { {_autoUpgradeProfileStatus = value;} } } + + /// Internal Acessors for AutoUpgradeProfileStatusLastTriggerError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.AutoUpgradeProfileStatusLastTriggerError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerError = value ?? null /* model class */; } + + /// Internal Acessors for AutoUpgradeProfileStatusLastTriggerStatus + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.AutoUpgradeProfileStatusLastTriggerStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerStatus = value ?? null; } + + /// Internal Acessors for AutoUpgradeProfileStatusLastTriggerUpgradeVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.AutoUpgradeProfileStatusLastTriggerUpgradeVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerUpgradeVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerUpgradeVersion = value ?? null /* arrayOf */; } + + /// Internal Acessors for AutoUpgradeProfileStatusLastTriggeredAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.AutoUpgradeProfileStatusLastTriggeredAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggeredAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggeredAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for LastTriggerErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.LastTriggerErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorAdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorAdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastTriggerErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.LastTriggerErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorCode = value ?? null; } + + /// Internal Acessors for LastTriggerErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.LastTriggerErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorDetail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastTriggerErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.LastTriggerErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorMessage = value ?? null; } + + /// Internal Acessors for LastTriggerErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.LastTriggerErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorTarget; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)AutoUpgradeProfileStatus).LastTriggerErrorTarget = value ?? null; } + + /// Internal Acessors for NodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.NodeImageSelection { get => (this._nodeImageSelection = this._nodeImageSelection ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelection()); set { {_nodeImageSelection = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfilePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection _nodeImageSelection; + + /// The node image upgrade to be applied to the target clusters in auto upgrade. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection NodeImageSelection { get => (this._nodeImageSelection = this._nodeImageSelection ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelection()); set => this._nodeImageSelection = value; } + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string NodeImageSelectionType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal)NodeImageSelection).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelectionInternal)NodeImageSelection).Type = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state of the AutoUpgradeProfile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _targetKubernetesVersion; + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". + /// By default, this is empty. + /// If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string TargetKubernetesVersion { get => this._targetKubernetesVersion; set => this._targetKubernetesVersion = value; } + + /// Backing field for property. + private string _updateStrategyId; + + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string UpdateStrategyId { get => this._updateStrategyId; set => this._updateStrategyId = value; } + + /// Creates an new instance. + public AutoUpgradeProfileProperties() + { + + } + } + /// The properties of the AutoUpgradeProfile. + public partial interface IAutoUpgradeProfileProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The status of the last AutoUpgrade trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last AutoUpgrade trigger.", + SerializedName = @"lastTriggerStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed")] + string AutoUpgradeProfileStatusLastTriggerStatus { get; } + /// The target Kubernetes version or node image versions of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The target Kubernetes version or node image versions of the last trigger.", + SerializedName = @"lastTriggerUpgradeVersions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AutoUpgradeProfileStatusLastTriggerUpgradeVersion { get; } + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions.", + SerializedName = @"lastTriggeredAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? AutoUpgradeProfileStatusLastTriggeredAt { get; } + /// Configures how auto-upgrade will be run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + string Channel { get; set; } + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + /// If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + /// This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + /// By default, this is set to False. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(bool) })] + bool? Disabled { get; set; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastTriggerErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorTarget { get; } + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. + /// If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + /// (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + /// By default, this is set to False. + /// For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. + If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + By default, this is set to False. + For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(bool) })] + bool? LongTermSupport { get; set; } + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + string NodeImageSelectionType { get; set; } + /// The provisioning state of the AutoUpgradeProfile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the AutoUpgradeProfile resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". + /// By default, this is empty. + /// If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". + By default, this is empty. + If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string TargetKubernetesVersion { get; set; } + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + string UpdateStrategyId { get; set; } + + } + /// The properties of the AutoUpgradeProfile. + internal partial interface IAutoUpgradeProfilePropertiesInternal + + { + /// The status of the auto upgrade profile. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus AutoUpgradeProfileStatus { get; set; } + /// The error details of the last trigger. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail AutoUpgradeProfileStatusLastTriggerError { get; set; } + /// The status of the last AutoUpgrade trigger. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed")] + string AutoUpgradeProfileStatusLastTriggerStatus { get; set; } + /// The target Kubernetes version or node image versions of the last trigger. + System.Collections.Generic.List AutoUpgradeProfileStatusLastTriggerUpgradeVersion { get; set; } + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + global::System.DateTime? AutoUpgradeProfileStatusLastTriggeredAt { get; set; } + /// Configures how auto-upgrade will be run. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + string Channel { get; set; } + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + /// If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + /// This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + /// By default, this is set to False. + /// + bool? Disabled { get; set; } + /// The error additional info. + System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get; set; } + /// The error code. + string LastTriggerErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastTriggerErrorDetail { get; set; } + /// The error message. + string LastTriggerErrorMessage { get; set; } + /// The error target. + string LastTriggerErrorTarget { get; set; } + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. + /// If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + /// (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + /// By default, this is set to False. + /// For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + bool? LongTermSupport { get; set; } + /// The node image upgrade to be applied to the target clusters in auto upgrade. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeNodeImageSelection NodeImageSelection { get; set; } + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + string NodeImageSelectionType { get; set; } + /// The provisioning state of the AutoUpgradeProfile resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". + /// By default, this is empty. + /// If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + string TargetKubernetesVersion { get; set; } + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + string UpdateStrategyId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.json.cs new file mode 100644 index 00000000000..ab2def50b3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the AutoUpgradeProfile. + public partial class AutoUpgradeProfileProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AutoUpgradeProfileProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nodeImageSelection = If( json?.PropertyT("nodeImageSelection"), out var __jsonNodeImageSelection) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeNodeImageSelection.FromJson(__jsonNodeImageSelection) : _nodeImageSelection;} + {_autoUpgradeProfileStatus = If( json?.PropertyT("autoUpgradeProfileStatus"), out var __jsonAutoUpgradeProfileStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfileStatus.FromJson(__jsonAutoUpgradeProfileStatus) : _autoUpgradeProfileStatus;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_updateStrategyId = If( json?.PropertyT("updateStrategyId"), out var __jsonUpdateStrategyId) ? (string)__jsonUpdateStrategyId : (string)_updateStrategyId;} + {_channel = If( json?.PropertyT("channel"), out var __jsonChannel) ? (string)__jsonChannel : (string)_channel;} + {_disabled = If( json?.PropertyT("disabled"), out var __jsonDisabled) ? (bool?)__jsonDisabled : _disabled;} + {_targetKubernetesVersion = If( json?.PropertyT("targetKubernetesVersion"), out var __jsonTargetKubernetesVersion) ? (string)__jsonTargetKubernetesVersion : (string)_targetKubernetesVersion;} + {_longTermSupport = If( json?.PropertyT("longTermSupport"), out var __jsonLongTermSupport) ? (bool?)__jsonLongTermSupport : _longTermSupport;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AutoUpgradeProfileProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._nodeImageSelection ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._nodeImageSelection.ToJson(null,serializationMode) : null, "nodeImageSelection" ,container.Add ); + AddIf( null != this._autoUpgradeProfileStatus ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._autoUpgradeProfileStatus.ToJson(null,serializationMode) : null, "autoUpgradeProfileStatus" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._updateStrategyId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._updateStrategyId.ToString()) : null, "updateStrategyId" ,container.Add ); + } + AddIf( null != (((object)this._channel)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._channel.ToString()) : null, "channel" ,container.Add ); + AddIf( null != this._disabled ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonBoolean((bool)this._disabled) : null, "disabled" ,container.Add ); + AddIf( null != (((object)this._targetKubernetesVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._targetKubernetesVersion.ToString()) : null, "targetKubernetesVersion" ,container.Add ); + AddIf( null != this._longTermSupport ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonBoolean((bool)this._longTermSupport) : null, "longTermSupport" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.PowerShell.cs new file mode 100644 index 00000000000..ca0d6f2e1cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// AutoUpgradeProfileStatus is the status of an auto upgrade profile. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileStatusTypeConverter))] + public partial class AutoUpgradeProfileStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 AutoUpgradeProfileStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("LastTriggerError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("LastTriggerError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("LastTriggeredAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggeredAt = (global::System.DateTime?) content.GetValueForProperty("LastTriggeredAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggeredAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTriggerStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerStatus = (string) content.GetValueForProperty("LastTriggerStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerStatus, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerUpgradeVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerUpgradeVersion = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerUpgradeVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerUpgradeVersion, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("LastTriggerErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorCode = (string) content.GetValueForProperty("LastTriggerErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorMessage = (string) content.GetValueForProperty("LastTriggerErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorTarget = (string) content.GetValueForProperty("LastTriggerErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastTriggerErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AutoUpgradeProfileStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("LastTriggerError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("LastTriggerError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("LastTriggeredAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggeredAt = (global::System.DateTime?) content.GetValueForProperty("LastTriggeredAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggeredAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastTriggerStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerStatus = (string) content.GetValueForProperty("LastTriggerStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerStatus, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerUpgradeVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerUpgradeVersion = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerUpgradeVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerUpgradeVersion, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("LastTriggerErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorCode = (string) content.GetValueForProperty("LastTriggerErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorMessage = (string) content.GetValueForProperty("LastTriggerErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorTarget = (string) content.GetValueForProperty("LastTriggerErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastTriggerErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastTriggerErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastTriggerErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal)this).LastTriggerErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.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.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AutoUpgradeProfileStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AutoUpgradeProfileStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// AutoUpgradeProfileStatus is the status of an auto upgrade profile. + [System.ComponentModel.TypeConverter(typeof(AutoUpgradeProfileStatusTypeConverter))] + public partial interface IAutoUpgradeProfileStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.TypeConverter.cs new file mode 100644 index 00000000000..c80278befb4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AutoUpgradeProfileStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AutoUpgradeProfileStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AutoUpgradeProfileStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AutoUpgradeProfileStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.cs new file mode 100644 index 00000000000..634ea99d574 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// AutoUpgradeProfileStatus is the status of an auto upgrade profile. + public partial class AutoUpgradeProfileStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail _lastTriggerError; + + /// The error details of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail LastTriggerError { get => (this._lastTriggerError = this._lastTriggerError ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastTriggerErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Message; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastTriggerErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Target; } + + /// Backing field for property. + private string _lastTriggerStatus; + + /// The status of the last AutoUpgrade trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string LastTriggerStatus { get => this._lastTriggerStatus; } + + /// Backing field for property. + private System.Collections.Generic.List _lastTriggerUpgradeVersion; + + /// The target Kubernetes version or node image versions of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List LastTriggerUpgradeVersion { get => this._lastTriggerUpgradeVersion; } + + /// Backing field for property. + private global::System.DateTime? _lastTriggeredAt; + + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public global::System.DateTime? LastTriggeredAt { get => this._lastTriggeredAt; } + + /// Internal Acessors for LastTriggerError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerError { get => (this._lastTriggerError = this._lastTriggerError ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); set { {_lastTriggerError = value;} } } + + /// Internal Acessors for LastTriggerErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastTriggerErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Code = value ?? null; } + + /// Internal Acessors for LastTriggerErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastTriggerErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Message = value ?? null; } + + /// Internal Acessors for LastTriggerErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastTriggerError).Target = value ?? null; } + + /// Internal Acessors for LastTriggerStatus + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerStatus { get => this._lastTriggerStatus; set { {_lastTriggerStatus = value;} } } + + /// Internal Acessors for LastTriggerUpgradeVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggerUpgradeVersion { get => this._lastTriggerUpgradeVersion; set { {_lastTriggerUpgradeVersion = value;} } } + + /// Internal Acessors for LastTriggeredAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatusInternal.LastTriggeredAt { get => this._lastTriggeredAt; set { {_lastTriggeredAt = value;} } } + + /// Creates an new instance. + public AutoUpgradeProfileStatus() + { + + } + } + /// AutoUpgradeProfileStatus is the status of an auto upgrade profile. + public partial interface IAutoUpgradeProfileStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastTriggerErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastTriggerErrorTarget { get; } + /// The status of the last AutoUpgrade trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last AutoUpgrade trigger.", + SerializedName = @"lastTriggerStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed")] + string LastTriggerStatus { get; } + /// The target Kubernetes version or node image versions of the last trigger. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The target Kubernetes version or node image versions of the last trigger.", + SerializedName = @"lastTriggerUpgradeVersions", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List LastTriggerUpgradeVersion { get; } + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions.", + SerializedName = @"lastTriggeredAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastTriggeredAt { get; } + + } + /// AutoUpgradeProfileStatus is the status of an auto upgrade profile. + internal partial interface IAutoUpgradeProfileStatusInternal + + { + /// The error details of the last trigger. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail LastTriggerError { get; set; } + /// The error additional info. + System.Collections.Generic.List LastTriggerErrorAdditionalInfo { get; set; } + /// The error code. + string LastTriggerErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastTriggerErrorDetail { get; set; } + /// The error message. + string LastTriggerErrorMessage { get; set; } + /// The error target. + string LastTriggerErrorTarget { get; set; } + /// The status of the last AutoUpgrade trigger. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed")] + string LastTriggerStatus { get; set; } + /// The target Kubernetes version or node image versions of the last trigger. + System.Collections.Generic.List LastTriggerUpgradeVersion { get; set; } + /// + /// The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions. + /// + global::System.DateTime? LastTriggeredAt { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.json.cs new file mode 100644 index 00000000000..33567404de8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/AutoUpgradeProfileStatus.json.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// AutoUpgradeProfileStatus is the status of an auto upgrade profile. + public partial class AutoUpgradeProfileStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal AutoUpgradeProfileStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_lastTriggerError = If( json?.PropertyT("lastTriggerError"), out var __jsonLastTriggerError) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail.FromJson(__jsonLastTriggerError) : _lastTriggerError;} + {_lastTriggeredAt = If( json?.PropertyT("lastTriggeredAt"), out var __jsonLastTriggeredAt) ? global::System.DateTime.TryParse((string)__jsonLastTriggeredAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastTriggeredAtValue) ? __jsonLastTriggeredAtValue : _lastTriggeredAt : _lastTriggeredAt;} + {_lastTriggerStatus = If( json?.PropertyT("lastTriggerStatus"), out var __jsonLastTriggerStatus) ? (string)__jsonLastTriggerStatus : (string)_lastTriggerStatus;} + {_lastTriggerUpgradeVersion = If( json?.PropertyT("lastTriggerUpgradeVersions"), out var __jsonLastTriggerUpgradeVersions) ? If( __jsonLastTriggerUpgradeVersions as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _lastTriggerUpgradeVersion;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfileStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new AutoUpgradeProfileStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastTriggerError ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._lastTriggerError.ToJson(null,serializationMode) : null, "lastTriggerError" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastTriggeredAt ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._lastTriggeredAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastTriggeredAt" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._lastTriggerStatus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._lastTriggerStatus.ToString()) : null, "lastTriggerStatus" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._lastTriggerUpgradeVersion) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._lastTriggerUpgradeVersion ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("lastTriggerUpgradeVersions",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.PowerShell.cs new file mode 100644 index 00000000000..a8ee1582fdc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ContainerServiceFleetIdentityTypeConverter))] + public partial class ContainerServiceFleetIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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 ContainerServiceFleetIdentity(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.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("FleetName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetName = (string) content.GetValueForProperty("FleetName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetName, global::System.Convert.ToString); + } + if (content.Contains("FleetMemberName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetMemberName = (string) content.GetValueForProperty("FleetMemberName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetMemberName, global::System.Convert.ToString); + } + if (content.Contains("GateName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).GateName = (string) content.GetValueForProperty("GateName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).GateName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateRunName = (string) content.GetValueForProperty("UpdateRunName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateRunName, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateStrategyName = (string) content.GetValueForProperty("UpdateStrategyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateStrategyName, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).AutoUpgradeProfileName = (string) content.GetValueForProperty("AutoUpgradeProfileName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).AutoUpgradeProfileName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)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 ContainerServiceFleetIdentity(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.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("FleetName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetName = (string) content.GetValueForProperty("FleetName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetName, global::System.Convert.ToString); + } + if (content.Contains("FleetMemberName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetMemberName = (string) content.GetValueForProperty("FleetMemberName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).FleetMemberName, global::System.Convert.ToString); + } + if (content.Contains("GateName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).GateName = (string) content.GetValueForProperty("GateName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).GateName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateRunName = (string) content.GetValueForProperty("UpdateRunName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateRunName, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateStrategyName = (string) content.GetValueForProperty("UpdateStrategyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).UpdateStrategyName, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).AutoUpgradeProfileName = (string) content.GetValueForProperty("AutoUpgradeProfileName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).AutoUpgradeProfileName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal)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.ContainerServiceFleet.Models.IContainerServiceFleetIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ContainerServiceFleetIdentity(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ContainerServiceFleetIdentity(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(ContainerServiceFleetIdentityTypeConverter))] + public partial interface IContainerServiceFleetIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.TypeConverter.cs new file mode 100644 index 00000000000..78697ec66c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ContainerServiceFleetIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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 ContainerServiceFleetIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ContainerServiceFleetIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ContainerServiceFleetIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ContainerServiceFleetIdentity.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.cs new file mode 100644 index 00000000000..1670b570b15 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.cs @@ -0,0 +1,209 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class ContainerServiceFleetIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentityInternal + { + + /// Backing field for property. + private string _autoUpgradeProfileName; + + /// The name of the AutoUpgradeProfile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string AutoUpgradeProfileName { get => this._autoUpgradeProfileName; set => this._autoUpgradeProfileName = value; } + + /// Backing field for property. + private string _fleetMemberName; + + /// The name of the Fleet member resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string FleetMemberName { get => this._fleetMemberName; set => this._fleetMemberName = value; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// Backing field for property. + private string _gateName; + + /// The name of the Gate resource, a GUID. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string GateName { get => this._gateName; set => this._gateName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateRunName; + + /// The name of the UpdateRun resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string UpdateRunName { get => this._updateRunName; set => this._updateRunName = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = value; } + + /// Creates an new instance. + public ContainerServiceFleetIdentity() + { + + } + } + public partial interface IContainerServiceFleetIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The name of the AutoUpgradeProfile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + string AutoUpgradeProfileName { get; set; } + /// The name of the Fleet member resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + string FleetMemberName { get; set; } + /// The name of the Fleet resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + string FleetName { get; set; } + /// The name of the Gate resource, a GUID. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + string GateName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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; } + /// The name of the UpdateRun resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunName { get; set; } + /// The name of the UpdateStrategy resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + string UpdateStrategyName { get; set; } + + } + internal partial interface IContainerServiceFleetIdentityInternal + + { + /// The name of the AutoUpgradeProfile resource. + string AutoUpgradeProfileName { get; set; } + /// The name of the Fleet member resource. + string FleetMemberName { get; set; } + /// The name of the Fleet resource. + string FleetName { get; set; } + /// The name of the Gate resource, a GUID. + string GateName { 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; } + /// The name of the UpdateRun resource. + string UpdateRunName { get; set; } + /// The name of the UpdateStrategy resource. + string UpdateStrategyName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.json.cs new file mode 100644 index 00000000000..13c153b17cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ContainerServiceFleetIdentity.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class ContainerServiceFleetIdentity + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ContainerServiceFleetIdentity(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_fleetName = If( json?.PropertyT("fleetName"), out var __jsonFleetName) ? (string)__jsonFleetName : (string)_fleetName;} + {_fleetMemberName = If( json?.PropertyT("fleetMemberName"), out var __jsonFleetMemberName) ? (string)__jsonFleetMemberName : (string)_fleetMemberName;} + {_gateName = If( json?.PropertyT("gateName"), out var __jsonGateName) ? (string)__jsonGateName : (string)_gateName;} + {_updateRunName = If( json?.PropertyT("updateRunName"), out var __jsonUpdateRunName) ? (string)__jsonUpdateRunName : (string)_updateRunName;} + {_updateStrategyName = If( json?.PropertyT("updateStrategyName"), out var __jsonUpdateStrategyName) ? (string)__jsonUpdateStrategyName : (string)_updateStrategyName;} + {_autoUpgradeProfileName = If( json?.PropertyT("autoUpgradeProfileName"), out var __jsonAutoUpgradeProfileName) ? (string)__jsonAutoUpgradeProfileName : (string)_autoUpgradeProfileName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ContainerServiceFleetIdentity(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._fleetName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._fleetName.ToString()) : null, "fleetName" ,container.Add ); + AddIf( null != (((object)this._fleetMemberName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._fleetMemberName.ToString()) : null, "fleetMemberName" ,container.Add ); + AddIf( null != (((object)this._gateName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._gateName.ToString()) : null, "gateName" ,container.Add ); + AddIf( null != (((object)this._updateRunName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._updateRunName.ToString()) : null, "updateRunName" ,container.Add ); + AddIf( null != (((object)this._updateStrategyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._updateStrategyName.ToString()) : null, "updateStrategyName" ,container.Add ); + AddIf( null != (((object)this._autoUpgradeProfileName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._autoUpgradeProfileName.ToString()) : null, "autoUpgradeProfileName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..0f8cce64026 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..f3f8c72fe49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..f1ecfde5aa5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..ab85c8d7843 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..ea3640a669c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..14b5f618f8a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..5cbeada48e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..c1d97130690 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..689910f1772 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..e94bbdff9bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..bf4d7fdc3b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Message = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Target = value ?? null; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..47d65372a91 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Fleet.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.PowerShell.cs new file mode 100644 index 00000000000..f91e1b55b2b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.PowerShell.cs @@ -0,0 +1,474 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The Fleet resource. + [System.ComponentModel.TypeConverter(typeof(FleetTypeConverter))] + public partial class Fleet + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleet DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Fleet(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Fleet(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Fleet(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.ContainerServiceFleet.Models.IFleetInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("HubProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile) content.GetValueForProperty("HubProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfileTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("HubProfileAgentProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileAgentProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile) content.GetValueForProperty("HubProfileAgentProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileAgentProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfileTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileApiServerAccessProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileApiServerAccessProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile) content.GetValueForProperty("HubProfileApiServerAccessProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileApiServerAccessProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfileTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileDnsPrefix")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileDnsPrefix = (string) content.GetValueForProperty("HubProfileDnsPrefix",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileDnsPrefix, global::System.Convert.ToString); + } + if (content.Contains("HubProfileFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileFqdn = (string) content.GetValueForProperty("HubProfileFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileFqdn, global::System.Convert.ToString); + } + if (content.Contains("HubProfileKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileKubernetesVersion = (string) content.GetValueForProperty("HubProfileKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("HubProfilePortalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfilePortalFqdn = (string) content.GetValueForProperty("HubProfilePortalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfilePortalFqdn, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileSubnetId = (string) content.GetValueForProperty("ApiServerAccessProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("AgentProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileSubnetId = (string) content.GetValueForProperty("AgentProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileEnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnablePrivateCluster = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ApiServerAccessProfileEnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnableVnetIntegration = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("AgentProfileVMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileVMSize = (string) content.GetValueForProperty("AgentProfileVMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileVMSize, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Fleet(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.ContainerServiceFleet.Models.IFleetInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("HubProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile) content.GetValueForProperty("HubProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfileTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("HubProfileAgentProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileAgentProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile) content.GetValueForProperty("HubProfileAgentProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileAgentProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfileTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileApiServerAccessProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileApiServerAccessProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile) content.GetValueForProperty("HubProfileApiServerAccessProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileApiServerAccessProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfileTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileDnsPrefix")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileDnsPrefix = (string) content.GetValueForProperty("HubProfileDnsPrefix",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileDnsPrefix, global::System.Convert.ToString); + } + if (content.Contains("HubProfileFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileFqdn = (string) content.GetValueForProperty("HubProfileFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileFqdn, global::System.Convert.ToString); + } + if (content.Contains("HubProfileKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileKubernetesVersion = (string) content.GetValueForProperty("HubProfileKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfileKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("HubProfilePortalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfilePortalFqdn = (string) content.GetValueForProperty("HubProfilePortalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).HubProfilePortalFqdn, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileSubnetId = (string) content.GetValueForProperty("ApiServerAccessProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("AgentProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileSubnetId = (string) content.GetValueForProperty("AgentProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileEnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnablePrivateCluster = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ApiServerAccessProfileEnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnableVnetIntegration = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).ApiServerAccessProfileEnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("AgentProfileVMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileVMSize = (string) content.GetValueForProperty("AgentProfileVMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).AgentProfileVMSize, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 Fleet resource. + [System.ComponentModel.TypeConverter(typeof(FleetTypeConverter))] + public partial interface IFleet + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.TypeConverter.cs new file mode 100644 index 00000000000..8f3eda43cd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleet ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Fleet.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Fleet.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Fleet.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/Fleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.cs new file mode 100644 index 00000000000..44e12de578d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.cs @@ -0,0 +1,630 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The Fleet resource. + public partial class Fleet : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResource(); + + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AgentProfileSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).AgentProfileSubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).AgentProfileSubnetId = value ?? null; } + + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AgentProfileVMSize { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).AgentProfileVMSize; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).AgentProfileVMSize = value ?? null; } + + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? ApiServerAccessProfileEnablePrivateCluster { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ApiServerAccessProfileEnablePrivateCluster; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ApiServerAccessProfileEnablePrivateCluster = value ?? default(bool); } + + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? ApiServerAccessProfileEnableVnetIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ApiServerAccessProfileEnableVnetIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ApiServerAccessProfileEnableVnetIntegration = value ?? default(bool); } + + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ApiServerAccessProfileSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ApiServerAccessProfileSubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ApiServerAccessProfileSubnetId = value ?? null; } + + /// Backing field for property. + private string _eTag; + + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// DNS prefix used to create the FQDN for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfileDnsPrefix { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileDnsPrefix; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileDnsPrefix = value ?? null; } + + /// The FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfileFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileFqdn; } + + /// The Kubernetes version of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfileKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileKubernetesVersion; } + + /// The Azure Portal FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfilePortalFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfilePortalFqdn; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity _identity; + + /// Managed identity. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorAdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorCode; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorDetail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorMessage; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorTarget; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)__trackedResource).Location = value ?? null; } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for HubProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.HubProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfile = value ?? null /* model class */; } + + /// Internal Acessors for HubProfileAgentProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.HubProfileAgentProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileAgentProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileAgentProfile = value ?? null /* model class */; } + + /// Internal Acessors for HubProfileApiServerAccessProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.HubProfileApiServerAccessProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileApiServerAccessProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileApiServerAccessProfile = value ?? null /* model class */; } + + /// Internal Acessors for HubProfileFqdn + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.HubProfileFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileFqdn; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileFqdn = value ?? null; } + + /// Internal Acessors for HubProfileKubernetesVersion + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.HubProfileKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileKubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfileKubernetesVersion = value ?? null; } + + /// Internal Acessors for HubProfilePortalFqdn + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.HubProfilePortalFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfilePortalFqdn; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).HubProfilePortalFqdn = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Internal Acessors for LastOperationErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorAdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorAdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorCode = value ?? null; } + + /// Internal Acessors for LastOperationErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorDetail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorMessage = value ?? null; } + + /// Internal Acessors for LastOperationErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorTarget; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).LastOperationErrorTarget = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).Status = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastOperationError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.StatusLastOperationError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).StatusLastOperationError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).StatusLastOperationError = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastOperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetInternal.StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).StatusLastOperationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).StatusLastOperationId = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetProperties()); set => this._property = value; } + + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// The last operation ID for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)Property).StatusLastOperationId; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public Fleet() + { + + } + + /// 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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// The Fleet resource. + public partial interface IFleet : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResource + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string AgentProfileSubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The virtual machine size of the Fleet hub.", + SerializedName = @"vmSize", + PossibleTypes = new [] { typeof(string) })] + string AgentProfileVMSize { get; set; } + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to create the Fleet hub as a private cluster or not.", + SerializedName = @"enablePrivateCluster", + PossibleTypes = new [] { typeof(bool) })] + bool? ApiServerAccessProfileEnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to enable apiserver vnet integration for the Fleet hub or not.", + SerializedName = @"enableVnetIntegration", + PossibleTypes = new [] { typeof(bool) })] + bool? ApiServerAccessProfileEnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string ApiServerAccessProfileSubnetId { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// DNS prefix used to create the FQDN for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"DNS prefix used to create the FQDN for the Fleet hub.", + SerializedName = @"dnsPrefix", + PossibleTypes = new [] { typeof(string) })] + string HubProfileDnsPrefix { get; set; } + /// The FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The FQDN of the Fleet hub.", + SerializedName = @"fqdn", + PossibleTypes = new [] { typeof(string) })] + string HubProfileFqdn { get; } + /// The Kubernetes version of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Kubernetes version of the Fleet hub.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string HubProfileKubernetesVersion { get; } + /// The Azure Portal FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Azure Portal FQDN of the Fleet hub.", + SerializedName = @"portalFqdn", + PossibleTypes = new [] { typeof(string) })] + string HubProfilePortalFqdn { get; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastOperationErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorTarget { get; } + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last operation.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; } + /// The last operation ID for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The last operation ID for the fleet.", + SerializedName = @"lastOperationId", + PossibleTypes = new [] { typeof(string) })] + string StatusLastOperationId { get; } + + } + /// The Fleet resource. + internal partial interface IFleetInternal : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + string AgentProfileSubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + string AgentProfileVMSize { get; set; } + /// Whether to create the Fleet hub as a private cluster or not. + bool? ApiServerAccessProfileEnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + bool? ApiServerAccessProfileEnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + string ApiServerAccessProfileSubnetId { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + string ETag { get; set; } + /// The FleetHubProfile configures the Fleet's hub. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile HubProfile { get; set; } + /// The agent profile for the Fleet hub. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile HubProfileAgentProfile { get; set; } + /// The access profile for the Fleet hub API server. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile HubProfileApiServerAccessProfile { get; set; } + /// DNS prefix used to create the FQDN for the Fleet hub. + string HubProfileDnsPrefix { get; set; } + /// The FQDN of the Fleet hub. + string HubProfileFqdn { get; set; } + /// The Kubernetes version of the Fleet hub. + string HubProfileKubernetesVersion { get; set; } + /// The Azure Portal FQDN of the Fleet hub. + string HubProfilePortalFqdn { get; set; } + /// Managed identity. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// The error additional info. + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; set; } + /// The error code. + string LastOperationErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastOperationErrorDetail { get; set; } + /// The error message. + string LastOperationErrorMessage { get; set; } + /// The error target. + string LastOperationErrorTarget { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties Property { get; set; } + /// The status of the last operation. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; set; } + /// Status information for the fleet. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus Status { get; set; } + /// The last operation error for the fleet. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusLastOperationError { get; set; } + /// The last operation ID for the fleet. + string StatusLastOperationId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.json.cs new file mode 100644 index 00000000000..10f59d552e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Fleet.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The Fleet resource. + public partial class Fleet + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal Fleet(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetProperties.FromJson(__jsonProperties) : _property;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)_eTag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new Fleet(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.PowerShell.cs new file mode 100644 index 00000000000..7218ab1ed66 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// One credential result item. + [System.ComponentModel.TypeConverter(typeof(FleetCredentialResultTypeConverter))] + public partial class FleetCredentialResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetCredentialResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetCredentialResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetCredentialResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetCredentialResult(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.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Value = (byte[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Value, i => i); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetCredentialResult(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.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Value = (byte[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal)this).Value, i => i); + } + 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.ContainerServiceFleet.Models.IFleetCredentialResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// One credential result item. + [System.ComponentModel.TypeConverter(typeof(FleetCredentialResultTypeConverter))] + public partial interface IFleetCredentialResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.TypeConverter.cs new file mode 100644 index 00000000000..65f35317b7c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetCredentialResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetCredentialResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetCredentialResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetCredentialResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetCredentialResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.cs new file mode 100644 index 00000000000..e9677f5ad59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// One credential result item. + public partial class FleetCredentialResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal + { + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Value + byte[] Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the credential. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private byte[] _value; + + /// Base64-encoded Kubernetes configuration file. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public byte[] Value { get => this._value; } + + /// Creates an new instance. + public FleetCredentialResult() + { + + } + } + /// One credential result item. + public partial interface IFleetCredentialResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The name of the credential. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the credential.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Base64-encoded Kubernetes configuration file. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Base64-encoded Kubernetes configuration file.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(byte[]) })] + byte[] Value { get; } + + } + /// One credential result item. + internal partial interface IFleetCredentialResultInternal + + { + /// The name of the credential. + string Name { get; set; } + /// Base64-encoded Kubernetes configuration file. + byte[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.json.cs new file mode 100644 index 00000000000..71d714209e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// One credential result item. + public partial class FleetCredentialResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetCredentialResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_value = If( json?.PropertyT("value"), out var __w) ? System.Convert.FromBase64String( ((string)__w).Replace("_","/").Replace("-","+").PadRight( ((string)__w).Length + ((string)__w).Length * 3 % 4, '=') ) : null;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetCredentialResult(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._value ? global::System.Convert.ToBase64String( this._value) : null ,(v)=> container.Add( "value",v) ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.PowerShell.cs new file mode 100644 index 00000000000..022508b9ece --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The Credential results response. + [System.ComponentModel.TypeConverter(typeof(FleetCredentialResultsTypeConverter))] + public partial class FleetCredentialResults + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetCredentialResults DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetCredentialResults(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetCredentialResults(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetCredentialResults(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Kubeconfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultsInternal)this).Kubeconfig = (System.Collections.Generic.List) content.GetValueForProperty("Kubeconfig",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultsInternal)this).Kubeconfig, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetCredentialResultTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetCredentialResults(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Kubeconfig")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultsInternal)this).Kubeconfig = (System.Collections.Generic.List) content.GetValueForProperty("Kubeconfig",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultsInternal)this).Kubeconfig, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetCredentialResultTypeConverter.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.ContainerServiceFleet.Models.IFleetCredentialResults FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 Credential results response. + [System.ComponentModel.TypeConverter(typeof(FleetCredentialResultsTypeConverter))] + public partial interface IFleetCredentialResults + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.TypeConverter.cs new file mode 100644 index 00000000000..d406a98721f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetCredentialResultsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetCredentialResults ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetCredentialResults.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetCredentialResults.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetCredentialResults.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.cs new file mode 100644 index 00000000000..2b6856aaac6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The Credential results response. + public partial class FleetCredentialResults : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultsInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _kubeconfig; + + /// Array of base64-encoded Kubernetes configuration files. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Kubeconfig { get => this._kubeconfig; } + + /// Internal Acessors for Kubeconfig + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResultsInternal.Kubeconfig { get => this._kubeconfig; set { {_kubeconfig = value;} } } + + /// Creates an new instance. + public FleetCredentialResults() + { + + } + } + /// The Credential results response. + public partial interface IFleetCredentialResults : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// Array of base64-encoded Kubernetes configuration files. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Array of base64-encoded Kubernetes configuration files.", + SerializedName = @"kubeconfigs", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResult) })] + System.Collections.Generic.List Kubeconfig { get; } + + } + /// The Credential results response. + internal partial interface IFleetCredentialResultsInternal + + { + /// Array of base64-encoded Kubernetes configuration files. + System.Collections.Generic.List Kubeconfig { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.json.cs new file mode 100644 index 00000000000..7ba43836d8d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetCredentialResults.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The Credential results response. + public partial class FleetCredentialResults + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetCredentialResults(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_kubeconfig = If( json?.PropertyT("kubeconfigs"), out var __jsonKubeconfigs) ? If( __jsonKubeconfigs as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetCredentialResult) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetCredentialResult.FromJson(__u) )) ))() : null : _kubeconfig;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetCredentialResults(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._kubeconfig) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._kubeconfig ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("kubeconfigs",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.PowerShell.cs new file mode 100644 index 00000000000..57870c53d2a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The FleetHubProfile configures the fleet hub. + [System.ComponentModel.TypeConverter(typeof(FleetHubProfileTypeConverter))] + public partial class FleetHubProfile + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetHubProfile DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetHubProfile(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetHubProfile(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetHubProfile(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ApiServerAccessProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile) content.GetValueForProperty("ApiServerAccessProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfileTypeConverter.ConvertFrom); + } + if (content.Contains("AgentProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile) content.GetValueForProperty("AgentProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfileTypeConverter.ConvertFrom); + } + if (content.Contains("DnsPrefix")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).DnsPrefix = (string) content.GetValueForProperty("DnsPrefix",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).DnsPrefix, global::System.Convert.ToString); + } + if (content.Contains("Fqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).Fqdn = (string) content.GetValueForProperty("Fqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).Fqdn, global::System.Convert.ToString); + } + if (content.Contains("KubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).KubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("PortalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).PortalFqdn = (string) content.GetValueForProperty("PortalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).PortalFqdn, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileSubnetId = (string) content.GetValueForProperty("ApiServerAccessProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("AgentProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileSubnetId = (string) content.GetValueForProperty("AgentProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileEnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnablePrivateCluster = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ApiServerAccessProfileEnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnableVnetIntegration = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("AgentProfileVMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileVMSize = (string) content.GetValueForProperty("AgentProfileVMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileVMSize, 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 FleetHubProfile(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ApiServerAccessProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile) content.GetValueForProperty("ApiServerAccessProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfileTypeConverter.ConvertFrom); + } + if (content.Contains("AgentProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile) content.GetValueForProperty("AgentProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfileTypeConverter.ConvertFrom); + } + if (content.Contains("DnsPrefix")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).DnsPrefix = (string) content.GetValueForProperty("DnsPrefix",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).DnsPrefix, global::System.Convert.ToString); + } + if (content.Contains("Fqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).Fqdn = (string) content.GetValueForProperty("Fqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).Fqdn, global::System.Convert.ToString); + } + if (content.Contains("KubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).KubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("PortalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).PortalFqdn = (string) content.GetValueForProperty("PortalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).PortalFqdn, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileSubnetId = (string) content.GetValueForProperty("ApiServerAccessProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("AgentProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileSubnetId = (string) content.GetValueForProperty("AgentProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileEnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnablePrivateCluster = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ApiServerAccessProfileEnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnableVnetIntegration = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).ApiServerAccessProfileEnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("AgentProfileVMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileVMSize = (string) content.GetValueForProperty("AgentProfileVMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)this).AgentProfileVMSize, 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.ContainerServiceFleet.Models.IFleetHubProfile FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetHubProfile configures the fleet hub. + [System.ComponentModel.TypeConverter(typeof(FleetHubProfileTypeConverter))] + public partial interface IFleetHubProfile + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.TypeConverter.cs new file mode 100644 index 00000000000..37536f1caf6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetHubProfileTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetHubProfile ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetHubProfile.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetHubProfile.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetHubProfile.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.cs new file mode 100644 index 00000000000..a6eb8cead07 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.cs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The FleetHubProfile configures the fleet hub. + public partial class FleetHubProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile _agentProfile; + + /// The agent profile for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile AgentProfile { get => (this._agentProfile = this._agentProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfile()); set => this._agentProfile = value; } + + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AgentProfileSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)AgentProfile).SubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)AgentProfile).SubnetId = value ?? null; } + + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AgentProfileVMSize { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)AgentProfile).VMSize; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfileInternal)AgentProfile).VMSize = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile _apiServerAccessProfile; + + /// The access profile for the Fleet hub API server. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile ApiServerAccessProfile { get => (this._apiServerAccessProfile = this._apiServerAccessProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfile()); set => this._apiServerAccessProfile = value; } + + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? ApiServerAccessProfileEnablePrivateCluster { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)ApiServerAccessProfile).EnablePrivateCluster; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)ApiServerAccessProfile).EnablePrivateCluster = value ?? default(bool); } + + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? ApiServerAccessProfileEnableVnetIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)ApiServerAccessProfile).EnableVnetIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)ApiServerAccessProfile).EnableVnetIntegration = value ?? default(bool); } + + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ApiServerAccessProfileSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)ApiServerAccessProfile).SubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfileInternal)ApiServerAccessProfile).SubnetId = value ?? null; } + + /// Backing field for property. + private string _dnsPrefix; + + /// DNS prefix used to create the FQDN for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string DnsPrefix { get => this._dnsPrefix; set => this._dnsPrefix = value; } + + /// Backing field for property. + private string _fqdn; + + /// The FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Fqdn { get => this._fqdn; } + + /// Backing field for property. + private string _kubernetesVersion; + + /// The Kubernetes version of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string KubernetesVersion { get => this._kubernetesVersion; } + + /// Internal Acessors for AgentProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal.AgentProfile { get => (this._agentProfile = this._agentProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfile()); set { {_agentProfile = value;} } } + + /// Internal Acessors for ApiServerAccessProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal.ApiServerAccessProfile { get => (this._apiServerAccessProfile = this._apiServerAccessProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfile()); set { {_apiServerAccessProfile = value;} } } + + /// Internal Acessors for Fqdn + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal.Fqdn { get => this._fqdn; set { {_fqdn = value;} } } + + /// Internal Acessors for KubernetesVersion + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal.KubernetesVersion { get => this._kubernetesVersion; set { {_kubernetesVersion = value;} } } + + /// Internal Acessors for PortalFqdn + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal.PortalFqdn { get => this._portalFqdn; set { {_portalFqdn = value;} } } + + /// Backing field for property. + private string _portalFqdn; + + /// The Azure Portal FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string PortalFqdn { get => this._portalFqdn; } + + /// Creates an new instance. + public FleetHubProfile() + { + + } + } + /// The FleetHubProfile configures the fleet hub. + public partial interface IFleetHubProfile : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string AgentProfileSubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The virtual machine size of the Fleet hub.", + SerializedName = @"vmSize", + PossibleTypes = new [] { typeof(string) })] + string AgentProfileVMSize { get; set; } + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to create the Fleet hub as a private cluster or not.", + SerializedName = @"enablePrivateCluster", + PossibleTypes = new [] { typeof(bool) })] + bool? ApiServerAccessProfileEnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to enable apiserver vnet integration for the Fleet hub or not.", + SerializedName = @"enableVnetIntegration", + PossibleTypes = new [] { typeof(bool) })] + bool? ApiServerAccessProfileEnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string ApiServerAccessProfileSubnetId { get; set; } + /// DNS prefix used to create the FQDN for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"DNS prefix used to create the FQDN for the Fleet hub.", + SerializedName = @"dnsPrefix", + PossibleTypes = new [] { typeof(string) })] + string DnsPrefix { get; set; } + /// The FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The FQDN of the Fleet hub.", + SerializedName = @"fqdn", + PossibleTypes = new [] { typeof(string) })] + string Fqdn { get; } + /// The Kubernetes version of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Kubernetes version of the Fleet hub.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string KubernetesVersion { get; } + /// The Azure Portal FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Azure Portal FQDN of the Fleet hub.", + SerializedName = @"portalFqdn", + PossibleTypes = new [] { typeof(string) })] + string PortalFqdn { get; } + + } + /// The FleetHubProfile configures the fleet hub. + internal partial interface IFleetHubProfileInternal + + { + /// The agent profile for the Fleet hub. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile AgentProfile { get; set; } + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + string AgentProfileSubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + string AgentProfileVMSize { get; set; } + /// The access profile for the Fleet hub API server. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile ApiServerAccessProfile { get; set; } + /// Whether to create the Fleet hub as a private cluster or not. + bool? ApiServerAccessProfileEnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + bool? ApiServerAccessProfileEnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + string ApiServerAccessProfileSubnetId { get; set; } + /// DNS prefix used to create the FQDN for the Fleet hub. + string DnsPrefix { get; set; } + /// The FQDN of the Fleet hub. + string Fqdn { get; set; } + /// The Kubernetes version of the Fleet hub. + string KubernetesVersion { get; set; } + /// The Azure Portal FQDN of the Fleet hub. + string PortalFqdn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.json.cs new file mode 100644 index 00000000000..330194c14dd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetHubProfile.json.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The FleetHubProfile configures the fleet hub. + public partial class FleetHubProfile + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetHubProfile(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_apiServerAccessProfile = If( json?.PropertyT("apiServerAccessProfile"), out var __jsonApiServerAccessProfile) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfile.FromJson(__jsonApiServerAccessProfile) : _apiServerAccessProfile;} + {_agentProfile = If( json?.PropertyT("agentProfile"), out var __jsonAgentProfile) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfile.FromJson(__jsonAgentProfile) : _agentProfile;} + {_dnsPrefix = If( json?.PropertyT("dnsPrefix"), out var __jsonDnsPrefix) ? (string)__jsonDnsPrefix : (string)_dnsPrefix;} + {_fqdn = If( json?.PropertyT("fqdn"), out var __jsonFqdn) ? (string)__jsonFqdn : (string)_fqdn;} + {_kubernetesVersion = If( json?.PropertyT("kubernetesVersion"), out var __jsonKubernetesVersion) ? (string)__jsonKubernetesVersion : (string)_kubernetesVersion;} + {_portalFqdn = If( json?.PropertyT("portalFqdn"), out var __jsonPortalFqdn) ? (string)__jsonPortalFqdn : (string)_portalFqdn;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetHubProfile(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._apiServerAccessProfile ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._apiServerAccessProfile.ToJson(null,serializationMode) : null, "apiServerAccessProfile" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._agentProfile ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._agentProfile.ToJson(null,serializationMode) : null, "agentProfile" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._dnsPrefix)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._dnsPrefix.ToString()) : null, "dnsPrefix" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._fqdn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._fqdn.ToString()) : null, "fqdn" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._kubernetesVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._kubernetesVersion.ToString()) : null, "kubernetesVersion" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._portalFqdn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._portalFqdn.ToString()) : null, "portalFqdn" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.PowerShell.cs new file mode 100644 index 00000000000..cfdde3fd49d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The response of a Fleet list operation. + [System.ComponentModel.TypeConverter(typeof(FleetListResultTypeConverter))] + public partial class FleetListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetListResult(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.ContainerServiceFleet.Models.IFleetListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal)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 FleetListResult(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.ContainerServiceFleet.Models.IFleetListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal)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.ContainerServiceFleet.Models.IFleetListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 Fleet list operation. + [System.ComponentModel.TypeConverter(typeof(FleetListResultTypeConverter))] + public partial interface IFleetListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.TypeConverter.cs new file mode 100644 index 00000000000..10b9c93931a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.cs new file mode 100644 index 00000000000..2159e9dafc5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a Fleet list operation. + public partial class FleetListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Fleet items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public FleetListResult() + { + + } + } + /// The response of a Fleet list operation. + public partial interface IFleetListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 Fleet items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Fleet items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a Fleet list operation. + internal partial interface IFleetListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Fleet items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.json.cs new file mode 100644 index 00000000000..4a9564a4a0c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a Fleet list operation. + public partial class FleetListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet.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.ContainerServiceFleet.Models.IFleetListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetListResult(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/FleetMember.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.PowerShell.cs new file mode 100644 index 00000000000..db58c460ab7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.PowerShell.cs @@ -0,0 +1,348 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + [System.ComponentModel.TypeConverter(typeof(FleetMemberTypeConverter))] + public partial class FleetMember + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMember DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMember(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMember(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMember(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.ContainerServiceFleet.Models.IFleetMemberInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ClusterResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ClusterResourceId = (string) content.GetValueForProperty("ClusterResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ClusterResourceId, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesLabelsTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetMember(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.ContainerServiceFleet.Models.IFleetMemberInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ClusterResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ClusterResourceId = (string) content.GetValueForProperty("ClusterResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ClusterResourceId, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesLabelsTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + [System.ComponentModel.TypeConverter(typeof(FleetMemberTypeConverter))] + public partial interface IFleetMember + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.TypeConverter.cs new file mode 100644 index 00000000000..6b269ba87fa --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMember ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMember.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMember.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMember.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMember.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.cs new file mode 100644 index 00000000000..c482273bfd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.cs @@ -0,0 +1,389 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + public partial class FleetMember : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(); + + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ClusterResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).ClusterResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).ClusterResourceId = value ?? null; } + + /// Backing field for property. + private string _eTag; + + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Group { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).Group; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).Group = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; } + + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).Label; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).Label = value ?? null /* model class */; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorAdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorCode; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorDetail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorMessage; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorTarget; } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for LastOperationErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorAdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorAdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorCode = value ?? null; } + + /// Internal Acessors for LastOperationErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorDetail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorMessage = value ?? null; } + + /// Internal Acessors for LastOperationErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorTarget; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).LastOperationErrorTarget = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).Status = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastOperationError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.StatusLastOperationError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).StatusLastOperationError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).StatusLastOperationError = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastOperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberInternal.StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).StatusLastOperationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).StatusLastOperationId = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberProperties()); set => this._property = value; } + + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// The last operation ID for the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)Property).StatusLastOperationId; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public FleetMember() + { + + } + + /// 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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + public partial interface IFleetMember : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource + { + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'.", + SerializedName = @"clusterResourceId", + PossibleTypes = new [] { typeof(string) })] + string ClusterResourceId { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string Group { get; set; } + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get; set; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastOperationErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorTarget { get; } + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last operation.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Joining", "Leaving", "Updating")] + string ProvisioningState { get; } + /// The last operation ID for the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The last operation ID for the fleet member", + SerializedName = @"lastOperationId", + PossibleTypes = new [] { typeof(string) })] + string StatusLastOperationId { get; } + + } + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + internal partial interface IFleetMemberInternal : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResourceInternal + { + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + string ClusterResourceId { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + string ETag { get; set; } + /// The group this member belongs to for multi-cluster update management. + string Group { get; set; } + /// The labels for the fleet member. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get; set; } + /// The error additional info. + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; set; } + /// The error code. + string LastOperationErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastOperationErrorDetail { get; set; } + /// The error message. + string LastOperationErrorMessage { get; set; } + /// The error target. + string LastOperationErrorTarget { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties Property { get; set; } + /// The status of the last operation. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Joining", "Leaving", "Updating")] + string ProvisioningState { get; set; } + /// Status information of the last operation for fleet member. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus Status { get; set; } + /// The last operation error of the fleet member + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusLastOperationError { get; set; } + /// The last operation ID for the fleet member + string StatusLastOperationId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.json.cs new file mode 100644 index 00000000000..66083ebd6d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMember.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + public partial class FleetMember + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetMember(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberProperties.FromJson(__jsonProperties) : _property;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)_eTag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMember(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.PowerShell.cs new file mode 100644 index 00000000000..281909cfd33 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The response of a FleetMember list operation. + [System.ComponentModel.TypeConverter(typeof(FleetMemberListResultTypeConverter))] + public partial class FleetMemberListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberListResult(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.ContainerServiceFleet.Models.IFleetMemberListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal)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 FleetMemberListResult(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.ContainerServiceFleet.Models.IFleetMemberListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal)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.ContainerServiceFleet.Models.IFleetMemberListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMember list operation. + [System.ComponentModel.TypeConverter(typeof(FleetMemberListResultTypeConverter))] + public partial interface IFleetMemberListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.TypeConverter.cs new file mode 100644 index 00000000000..25683a12259 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.cs new file mode 100644 index 00000000000..19928e070d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a FleetMember list operation. + public partial class FleetMemberListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The FleetMember items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public FleetMemberListResult() + { + + } + } + /// The response of a FleetMember list operation. + public partial interface IFleetMemberListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetMember items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The FleetMember items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a FleetMember list operation. + internal partial interface IFleetMemberListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The FleetMember items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.json.cs new file mode 100644 index 00000000000..460d7ba468f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a FleetMember list operation. + public partial class FleetMemberListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetMemberListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember.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.ContainerServiceFleet.Models.IFleetMemberListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberListResult(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.PowerShell.cs new file mode 100644 index 00000000000..3a63486121e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + [System.ComponentModel.TypeConverter(typeof(FleetMemberPropertiesTypeConverter))] + public partial class FleetMemberProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ClusterResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ClusterResourceId = (string) content.GetValueForProperty("ClusterResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ClusterResourceId, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesLabelsTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetMemberProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ClusterResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ClusterResourceId = (string) content.GetValueForProperty("ClusterResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ClusterResourceId, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesLabelsTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMemberProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + [System.ComponentModel.TypeConverter(typeof(FleetMemberPropertiesTypeConverter))] + public partial interface IFleetMemberProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.TypeConverter.cs new file mode 100644 index 00000000000..55d0bffc378 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.cs new file mode 100644 index 00000000000..0d139e79b90 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + public partial class FleetMemberProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal + { + + /// Backing field for property. + private string _clusterResourceId; + + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ClusterResourceId { get => this._clusterResourceId; set => this._clusterResourceId = value; } + + /// Backing field for property. + private string _group; + + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Group { get => this._group; set => this._group = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels _label; + + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get => (this._label = this._label ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesLabels()); set => this._label = value; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorAdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorCode; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorDetail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorMessage; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorTarget; } + + /// Internal Acessors for LastOperationErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorAdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorAdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorCode = value ?? null; } + + /// Internal Acessors for LastOperationErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorDetail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorMessage = value ?? null; } + + /// Internal Acessors for LastOperationErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorTarget; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationErrorTarget = value ?? null; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusLastOperationError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.StatusLastOperationError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationError = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastOperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesInternal.StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationId = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus _status; + + /// Status information of the last operation for fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatus()); } + + /// The last operation ID for the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)Status).LastOperationId; } + + /// Creates an new instance. + public FleetMemberProperties() + { + + } + } + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + public partial interface IFleetMemberProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'.", + SerializedName = @"clusterResourceId", + PossibleTypes = new [] { typeof(string) })] + string ClusterResourceId { get; set; } + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string Group { get; set; } + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get; set; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastOperationErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorTarget { get; } + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last operation.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Joining", "Leaving", "Updating")] + string ProvisioningState { get; } + /// The last operation ID for the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The last operation ID for the fleet member", + SerializedName = @"lastOperationId", + PossibleTypes = new [] { typeof(string) })] + string StatusLastOperationId { get; } + + } + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + internal partial interface IFleetMemberPropertiesInternal + + { + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + string ClusterResourceId { get; set; } + /// The group this member belongs to for multi-cluster update management. + string Group { get; set; } + /// The labels for the fleet member. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get; set; } + /// The error additional info. + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; set; } + /// The error code. + string LastOperationErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastOperationErrorDetail { get; set; } + /// The error message. + string LastOperationErrorMessage { get; set; } + /// The error target. + string LastOperationErrorTarget { get; set; } + /// The status of the last operation. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Joining", "Leaving", "Updating")] + string ProvisioningState { get; set; } + /// Status information of the last operation for fleet member. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus Status { get; set; } + /// The last operation error of the fleet member + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusLastOperationError { get; set; } + /// The last operation ID for the fleet member + string StatusLastOperationId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.json.cs new file mode 100644 index 00000000000..475346eefed --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// A member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + public partial class FleetMemberProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetMemberProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberStatus.FromJson(__jsonStatus) : _status;} + {_clusterResourceId = If( json?.PropertyT("clusterResourceId"), out var __jsonClusterResourceId) ? (string)__jsonClusterResourceId : (string)_clusterResourceId;} + {_group = If( json?.PropertyT("group"), out var __jsonGroup) ? (string)__jsonGroup : (string)_group;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_label = If( json?.PropertyT("labels"), out var __jsonLabels) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberPropertiesLabels.FromJson(__jsonLabels) : _label;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._clusterResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._clusterResourceId.ToString()) : null, "clusterResourceId" ,container.Add ); + } + AddIf( null != (((object)this._group)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._group.ToString()) : null, "group" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AddIf( null != this._label ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._label.ToJson(null,serializationMode) : null, "labels" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.PowerShell.cs new file mode 100644 index 00000000000..491e2b70f3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.PowerShell.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The labels for the fleet member. + [System.ComponentModel.TypeConverter(typeof(FleetMemberPropertiesLabelsTypeConverter))] + public partial class FleetMemberPropertiesLabels + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberPropertiesLabels(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberPropertiesLabels(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberPropertiesLabels(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 FleetMemberPropertiesLabels(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); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 labels for the fleet member. + [System.ComponentModel.TypeConverter(typeof(FleetMemberPropertiesLabelsTypeConverter))] + public partial interface IFleetMemberPropertiesLabels + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.TypeConverter.cs new file mode 100644 index 00000000000..17dddc1e81e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberPropertiesLabelsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberPropertiesLabels.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberPropertiesLabels.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberPropertiesLabels.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.cs new file mode 100644 index 00000000000..4eb63d0eb58 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The labels for the fleet member. + public partial class FleetMemberPropertiesLabels : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabelsInternal + { + + /// Creates an new instance. + public FleetMemberPropertiesLabels() + { + + } + } + /// The labels for the fleet member. + public partial interface IFleetMemberPropertiesLabels : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + + } + /// The labels for the fleet member. + internal partial interface IFleetMemberPropertiesLabelsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.dictionary.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.dictionary.cs new file mode 100644 index 00000000000..aa0e7c21b67 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class FleetMemberPropertiesLabels : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.FleetMemberPropertiesLabels source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.json.cs new file mode 100644 index 00000000000..30f3751591c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberPropertiesLabels.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The labels for the fleet member. + public partial class FleetMemberPropertiesLabels + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + /// + internal FleetMemberPropertiesLabels(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberPropertiesLabels(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.PowerShell.cs new file mode 100644 index 00000000000..99011cd449a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Status information for the fleet member + [System.ComponentModel.TypeConverter(typeof(FleetMemberStatusTypeConverter))] + public partial class FleetMemberStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberStatus(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("LastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("LastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("LastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationId = (string) content.GetValueForProperty("LastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetMemberStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("LastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("LastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("LastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationId = (string) content.GetValueForProperty("LastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMemberStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// Status information for the fleet member + [System.ComponentModel.TypeConverter(typeof(FleetMemberStatusTypeConverter))] + public partial interface IFleetMemberStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.TypeConverter.cs new file mode 100644 index 00000000000..7c0b0c3fbe0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.cs new file mode 100644 index 00000000000..8f504465763 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Status information for the fleet member + public partial class FleetMemberStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail _lastOperationError; + + /// The last operation error of the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail LastOperationError { get => (this._lastOperationError = this._lastOperationError ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Message; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Target; } + + /// Backing field for property. + private string _lastOperationId; + + /// The last operation ID for the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string LastOperationId { get => this._lastOperationId; } + + /// Internal Acessors for LastOperationError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationError { get => (this._lastOperationError = this._lastOperationError ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); set { {_lastOperationError = value;} } } + + /// Internal Acessors for LastOperationErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Code = value ?? null; } + + /// Internal Acessors for LastOperationErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Message = value ?? null; } + + /// Internal Acessors for LastOperationErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Target = value ?? null; } + + /// Internal Acessors for LastOperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatusInternal.LastOperationId { get => this._lastOperationId; set { {_lastOperationId = value;} } } + + /// Creates an new instance. + public FleetMemberStatus() + { + + } + } + /// Status information for the fleet member + public partial interface IFleetMemberStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastOperationErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorTarget { get; } + /// The last operation ID for the fleet member + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The last operation ID for the fleet member", + SerializedName = @"lastOperationId", + PossibleTypes = new [] { typeof(string) })] + string LastOperationId { get; } + + } + /// Status information for the fleet member + internal partial interface IFleetMemberStatusInternal + + { + /// The last operation error of the fleet member + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail LastOperationError { get; set; } + /// The error additional info. + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; set; } + /// The error code. + string LastOperationErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastOperationErrorDetail { get; set; } + /// The error message. + string LastOperationErrorMessage { get; set; } + /// The error target. + string LastOperationErrorTarget { get; set; } + /// The last operation ID for the fleet member + string LastOperationId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.json.cs new file mode 100644 index 00000000000..a3c9fa80ef7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberStatus.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Status information for the fleet member + public partial class FleetMemberStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetMemberStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_lastOperationError = If( json?.PropertyT("lastOperationError"), out var __jsonLastOperationError) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail.FromJson(__jsonLastOperationError) : _lastOperationError;} + {_lastOperationId = If( json?.PropertyT("lastOperationId"), out var __jsonLastOperationId) ? (string)__jsonLastOperationId : (string)_lastOperationId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastOperationError ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._lastOperationError.ToJson(null,serializationMode) : null, "lastOperationError" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._lastOperationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._lastOperationId.ToString()) : null, "lastOperationId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.PowerShell.cs new file mode 100644 index 00000000000..6258c50485a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The type used for update operations of the FleetMember. + [System.ComponentModel.TypeConverter(typeof(FleetMemberUpdateTypeConverter))] + public partial class FleetMemberUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberUpdate(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberUpdate(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.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabelsTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetMemberUpdate(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.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabelsTypeConverter.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.ContainerServiceFleet.Models.IFleetMemberUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMember. + [System.ComponentModel.TypeConverter(typeof(FleetMemberUpdateTypeConverter))] + public partial interface IFleetMemberUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.TypeConverter.cs new file mode 100644 index 00000000000..368c714aacb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.cs new file mode 100644 index 00000000000..4dbfa3660f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The type used for update operations of the FleetMember. + public partial class FleetMemberUpdate : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal + { + + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Group { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)Property).Group; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)Property).Group = value ?? null; } + + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)Property).Label; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)Property).Label = value ?? null /* model class */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdateProperties()); set { {_property = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdateProperties()); set => this._property = value; } + + /// Creates an new instance. + public FleetMemberUpdate() + { + + } + } + /// The type used for update operations of the FleetMember. + public partial interface IFleetMemberUpdate : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string Group { get; set; } + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get; set; } + + } + /// The type used for update operations of the FleetMember. + internal partial interface IFleetMemberUpdateInternal + + { + /// The group this member belongs to for multi-cluster update management. + string Group { get; set; } + /// The labels for the fleet member. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties Property { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.json.cs new file mode 100644 index 00000000000..db4bcbb7680 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdate.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The type used for update operations of the FleetMember. + public partial class FleetMemberUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetMemberUpdate(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.FleetMemberUpdateProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberUpdate(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.PowerShell.cs new file mode 100644 index 00000000000..621f7e7fbf5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The updatable properties of the FleetMember. + [System.ComponentModel.TypeConverter(typeof(FleetMemberUpdatePropertiesTypeConverter))] + public partial class FleetMemberUpdateProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberUpdateProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberUpdateProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberUpdateProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberUpdateProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabelsTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetMemberUpdateProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("Label")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Label = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal)this).Label, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabelsTypeConverter.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.ContainerServiceFleet.Models.IFleetMemberUpdateProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetMember. + [System.ComponentModel.TypeConverter(typeof(FleetMemberUpdatePropertiesTypeConverter))] + public partial interface IFleetMemberUpdateProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.TypeConverter.cs new file mode 100644 index 00000000000..9b526abf2bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberUpdatePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberUpdateProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberUpdateProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberUpdateProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberUpdateProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.cs new file mode 100644 index 00000000000..b73d34c9b5f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The updatable properties of the FleetMember. + public partial class FleetMemberUpdateProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesInternal + { + + /// Backing field for property. + private string _group; + + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Group { get => this._group; set => this._group = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels _label; + + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get => (this._label = this._label ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabels()); set => this._label = value; } + + /// Creates an new instance. + public FleetMemberUpdateProperties() + { + + } + } + /// The updatable properties of the FleetMember. + public partial interface IFleetMemberUpdateProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The group this member belongs to for multi-cluster update management. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string Group { get; set; } + /// The labels for the fleet member. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get; set; } + + } + /// The updatable properties of the FleetMember. + internal partial interface IFleetMemberUpdatePropertiesInternal + + { + /// The group this member belongs to for multi-cluster update management. + string Group { get; set; } + /// The labels for the fleet member. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.json.cs new file mode 100644 index 00000000000..8ac9c7e9eb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdateProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The updatable properties of the FleetMember. + public partial class FleetMemberUpdateProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetMemberUpdateProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_group = If( json?.PropertyT("group"), out var __jsonGroup) ? (string)__jsonGroup : (string)_group;} + {_label = If( json?.PropertyT("labels"), out var __jsonLabels) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabels.FromJson(__jsonLabels) : _label;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdateProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberUpdateProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._group)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._group.ToString()) : null, "group" ,container.Add ); + AddIf( null != this._label ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._label.ToJson(null,serializationMode) : null, "labels" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.PowerShell.cs new file mode 100644 index 00000000000..ca4ce0771a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The labels for the fleet member. + [System.ComponentModel.TypeConverter(typeof(FleetMemberUpdatePropertiesLabelsTypeConverter))] + public partial class FleetMemberUpdatePropertiesLabels + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetMemberUpdatePropertiesLabels(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetMemberUpdatePropertiesLabels(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetMemberUpdatePropertiesLabels(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 FleetMemberUpdatePropertiesLabels(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); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 labels for the fleet member. + [System.ComponentModel.TypeConverter(typeof(FleetMemberUpdatePropertiesLabelsTypeConverter))] + public partial interface IFleetMemberUpdatePropertiesLabels + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.TypeConverter.cs new file mode 100644 index 00000000000..003f05e19b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetMemberUpdatePropertiesLabelsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetMemberUpdatePropertiesLabels.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetMemberUpdatePropertiesLabels.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetMemberUpdatePropertiesLabels.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.cs new file mode 100644 index 00000000000..0fca490c39d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The labels for the fleet member. + public partial class FleetMemberUpdatePropertiesLabels : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabelsInternal + { + + /// Creates an new instance. + public FleetMemberUpdatePropertiesLabels() + { + + } + } + /// The labels for the fleet member. + public partial interface IFleetMemberUpdatePropertiesLabels : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + + } + /// The labels for the fleet member. + internal partial interface IFleetMemberUpdatePropertiesLabelsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.dictionary.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.dictionary.cs new file mode 100644 index 00000000000..f474912a6f5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class FleetMemberUpdatePropertiesLabels : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.FleetMemberUpdatePropertiesLabels source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.json.cs new file mode 100644 index 00000000000..feb40804815 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetMemberUpdatePropertiesLabels.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The labels for the fleet member. + public partial class FleetMemberUpdatePropertiesLabels + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + /// + internal FleetMemberUpdatePropertiesLabels(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetMemberUpdatePropertiesLabels(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.PowerShell.cs new file mode 100644 index 00000000000..58f86e37e72 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Properties of a Fleet that can be patched. + [System.ComponentModel.TypeConverter(typeof(FleetPatchTypeConverter))] + public partial class FleetPatch + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetPatch DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetPatch(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetPatch(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetPatch(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.ContainerServiceFleet.Models.IFleetPatchInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetPatchTagsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetPatch(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.ContainerServiceFleet.Models.IFleetPatchInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetPatchTagsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.ContainerServiceFleet.Models.IFleetPatch FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 a Fleet that can be patched. + [System.ComponentModel.TypeConverter(typeof(FleetPatchTypeConverter))] + public partial interface IFleetPatch + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.TypeConverter.cs new file mode 100644 index 00000000000..763be091b7c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetPatchTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetPatch ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetPatch.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetPatch.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetPatch.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetPatch.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.cs new file mode 100644 index 00000000000..e9dda832497 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Properties of a Fleet that can be patched. + public partial class FleetPatch : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity _identity; + + /// Managed identity. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value ?? null; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)Identity).TenantId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetPatchTags()); set => this._tag = value; } + + /// Creates an new instance. + public FleetPatch() + { + + } + } + /// Properties of a Fleet that can be patched. + public partial interface IFleetPatch : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags Tag { get; set; } + + } + /// Properties of a Fleet that can be patched. + internal partial interface IFleetPatchInternal + + { + /// Managed identity. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.json.cs new file mode 100644 index 00000000000..5116072d233 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatch.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Properties of a Fleet that can be patched. + public partial class FleetPatch + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetPatch(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetPatchTags.FromJson(__jsonTags) : _tag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatch FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetPatch(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.PowerShell.cs new file mode 100644 index 00000000000..62d42b59273 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(FleetPatchTagsTypeConverter))] + public partial class FleetPatchTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetPatchTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetPatchTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetPatchTags(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetPatchTags(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 FleetPatchTags(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); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(FleetPatchTagsTypeConverter))] + public partial interface IFleetPatchTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.TypeConverter.cs new file mode 100644 index 00000000000..e617b0e64e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetPatchTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetPatchTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetPatchTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetPatchTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetPatchTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.cs new file mode 100644 index 00000000000..87c7132cb12 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Resource tags. + public partial class FleetPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTagsInternal + { + + /// Creates an new instance. + public FleetPatchTags() + { + + } + } + /// Resource tags. + public partial interface IFleetPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface IFleetPatchTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.dictionary.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.dictionary.cs new file mode 100644 index 00000000000..279c9ba1458 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class FleetPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.FleetPatchTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.json.cs new file mode 100644 index 00000000000..2b4eec1bdf5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetPatchTags.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Resource tags. + public partial class FleetPatchTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + /// + internal FleetPatchTags(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPatchTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetPatchTags(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.PowerShell.cs new file mode 100644 index 00000000000..818e570ba22 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.PowerShell.cs @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Fleet properties. + [System.ComponentModel.TypeConverter(typeof(FleetPropertiesTypeConverter))] + public partial class FleetProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("HubProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile) content.GetValueForProperty("HubProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfileTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("HubProfileAgentProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileAgentProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile) content.GetValueForProperty("HubProfileAgentProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileAgentProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfileTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileApiServerAccessProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileApiServerAccessProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile) content.GetValueForProperty("HubProfileApiServerAccessProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileApiServerAccessProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfileTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileDnsPrefix")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileDnsPrefix = (string) content.GetValueForProperty("HubProfileDnsPrefix",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileDnsPrefix, global::System.Convert.ToString); + } + if (content.Contains("HubProfileFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileFqdn = (string) content.GetValueForProperty("HubProfileFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileFqdn, global::System.Convert.ToString); + } + if (content.Contains("HubProfileKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileKubernetesVersion = (string) content.GetValueForProperty("HubProfileKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("HubProfilePortalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfilePortalFqdn = (string) content.GetValueForProperty("HubProfilePortalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfilePortalFqdn, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileSubnetId = (string) content.GetValueForProperty("ApiServerAccessProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("AgentProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileSubnetId = (string) content.GetValueForProperty("AgentProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileEnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnablePrivateCluster = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ApiServerAccessProfileEnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnableVnetIntegration = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("AgentProfileVMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileVMSize = (string) content.GetValueForProperty("AgentProfileVMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileVMSize, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("HubProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile) content.GetValueForProperty("HubProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfileTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("HubProfileAgentProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileAgentProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile) content.GetValueForProperty("HubProfileAgentProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileAgentProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AgentProfileTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileApiServerAccessProfile")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileApiServerAccessProfile = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile) content.GetValueForProperty("HubProfileApiServerAccessProfile",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileApiServerAccessProfile, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ApiServerAccessProfileTypeConverter.ConvertFrom); + } + if (content.Contains("HubProfileDnsPrefix")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileDnsPrefix = (string) content.GetValueForProperty("HubProfileDnsPrefix",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileDnsPrefix, global::System.Convert.ToString); + } + if (content.Contains("HubProfileFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileFqdn = (string) content.GetValueForProperty("HubProfileFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileFqdn, global::System.Convert.ToString); + } + if (content.Contains("HubProfileKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileKubernetesVersion = (string) content.GetValueForProperty("HubProfileKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfileKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("HubProfilePortalFqdn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfilePortalFqdn = (string) content.GetValueForProperty("HubProfilePortalFqdn",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).HubProfilePortalFqdn, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileSubnetId = (string) content.GetValueForProperty("ApiServerAccessProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("AgentProfileSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileSubnetId = (string) content.GetValueForProperty("AgentProfileSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileSubnetId, global::System.Convert.ToString); + } + if (content.Contains("StatusLastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusLastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusLastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationId = (string) content.GetValueForProperty("StatusLastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).StatusLastOperationId, global::System.Convert.ToString); + } + if (content.Contains("ApiServerAccessProfileEnablePrivateCluster")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnablePrivateCluster = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnablePrivateCluster",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnablePrivateCluster, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("ApiServerAccessProfileEnableVnetIntegration")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnableVnetIntegration = (bool?) content.GetValueForProperty("ApiServerAccessProfileEnableVnetIntegration",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).ApiServerAccessProfileEnableVnetIntegration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("AgentProfileVMSize")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileVMSize = (string) content.GetValueForProperty("AgentProfileVMSize",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).AgentProfileVMSize, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// Fleet properties. + [System.ComponentModel.TypeConverter(typeof(FleetPropertiesTypeConverter))] + public partial interface IFleetProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.TypeConverter.cs new file mode 100644 index 00000000000..bbe11f539fa --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.cs new file mode 100644 index 00000000000..6b3e380b9c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.cs @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Fleet properties. + public partial class FleetProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal + { + + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AgentProfileSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).AgentProfileSubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).AgentProfileSubnetId = value ?? null; } + + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AgentProfileVMSize { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).AgentProfileVMSize; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).AgentProfileVMSize = value ?? null; } + + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? ApiServerAccessProfileEnablePrivateCluster { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfileEnablePrivateCluster; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfileEnablePrivateCluster = value ?? default(bool); } + + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public bool? ApiServerAccessProfileEnableVnetIntegration { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfileEnableVnetIntegration; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfileEnableVnetIntegration = value ?? default(bool); } + + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ApiServerAccessProfileSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfileSubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfileSubnetId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile _hubProfile; + + /// The FleetHubProfile configures the Fleet's hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile HubProfile { get => (this._hubProfile = this._hubProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfile()); set => this._hubProfile = value; } + + /// DNS prefix used to create the FQDN for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfileDnsPrefix { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).DnsPrefix; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).DnsPrefix = value ?? null; } + + /// The FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfileFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).Fqdn; } + + /// The Kubernetes version of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfileKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).KubernetesVersion; } + + /// The Azure Portal FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string HubProfilePortalFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).PortalFqdn; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorAdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorCode; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorDetail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorMessage; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorTarget; } + + /// Internal Acessors for HubProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.HubProfile { get => (this._hubProfile = this._hubProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfile()); set { {_hubProfile = value;} } } + + /// Internal Acessors for HubProfileAgentProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.HubProfileAgentProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).AgentProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).AgentProfile = value ?? null /* model class */; } + + /// Internal Acessors for HubProfileApiServerAccessProfile + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.HubProfileApiServerAccessProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).ApiServerAccessProfile = value ?? null /* model class */; } + + /// Internal Acessors for HubProfileFqdn + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.HubProfileFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).Fqdn; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).Fqdn = value ?? null; } + + /// Internal Acessors for HubProfileKubernetesVersion + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.HubProfileKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).KubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).KubernetesVersion = value ?? null; } + + /// Internal Acessors for HubProfilePortalFqdn + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.HubProfilePortalFqdn { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).PortalFqdn; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfileInternal)HubProfile).PortalFqdn = value ?? null; } + + /// Internal Acessors for LastOperationErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorAdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorAdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorCode = value ?? null; } + + /// Internal Acessors for LastOperationErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorDetail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorMessage = value ?? null; } + + /// Internal Acessors for LastOperationErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorTarget; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationErrorTarget = value ?? null; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusLastOperationError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.StatusLastOperationError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationError = value ?? null /* model class */; } + + /// Internal Acessors for StatusLastOperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetPropertiesInternal.StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationId = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus _status; + + /// Status information for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatus()); } + + /// The last operation ID for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusLastOperationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)Status).LastOperationId; } + + /// Creates an new instance. + public FleetProperties() + { + + } + } + /// Fleet properties. + public partial interface IFleetProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string AgentProfileSubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The virtual machine size of the Fleet hub.", + SerializedName = @"vmSize", + PossibleTypes = new [] { typeof(string) })] + string AgentProfileVMSize { get; set; } + /// Whether to create the Fleet hub as a private cluster or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to create the Fleet hub as a private cluster or not.", + SerializedName = @"enablePrivateCluster", + PossibleTypes = new [] { typeof(bool) })] + bool? ApiServerAccessProfileEnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether to enable apiserver vnet integration for the Fleet hub or not.", + SerializedName = @"enableVnetIntegration", + PossibleTypes = new [] { typeof(bool) })] + bool? ApiServerAccessProfileEnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + string ApiServerAccessProfileSubnetId { get; set; } + /// DNS prefix used to create the FQDN for the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"DNS prefix used to create the FQDN for the Fleet hub.", + SerializedName = @"dnsPrefix", + PossibleTypes = new [] { typeof(string) })] + string HubProfileDnsPrefix { get; set; } + /// The FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The FQDN of the Fleet hub.", + SerializedName = @"fqdn", + PossibleTypes = new [] { typeof(string) })] + string HubProfileFqdn { get; } + /// The Kubernetes version of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Kubernetes version of the Fleet hub.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string HubProfileKubernetesVersion { get; } + /// The Azure Portal FQDN of the Fleet hub. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Azure Portal FQDN of the Fleet hub.", + SerializedName = @"portalFqdn", + PossibleTypes = new [] { typeof(string) })] + string HubProfilePortalFqdn { get; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastOperationErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorTarget { get; } + /// The status of the last operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status of the last operation.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; } + /// The last operation ID for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The last operation ID for the fleet.", + SerializedName = @"lastOperationId", + PossibleTypes = new [] { typeof(string) })] + string StatusLastOperationId { get; } + + } + /// Fleet properties. + internal partial interface IFleetPropertiesInternal + + { + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + string AgentProfileSubnetId { get; set; } + /// The virtual machine size of the Fleet hub. + string AgentProfileVMSize { get; set; } + /// Whether to create the Fleet hub as a private cluster or not. + bool? ApiServerAccessProfileEnablePrivateCluster { get; set; } + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + bool? ApiServerAccessProfileEnableVnetIntegration { get; set; } + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + string ApiServerAccessProfileSubnetId { get; set; } + /// The FleetHubProfile configures the Fleet's hub. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetHubProfile HubProfile { get; set; } + /// The agent profile for the Fleet hub. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAgentProfile HubProfileAgentProfile { get; set; } + /// The access profile for the Fleet hub API server. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IApiServerAccessProfile HubProfileApiServerAccessProfile { get; set; } + /// DNS prefix used to create the FQDN for the Fleet hub. + string HubProfileDnsPrefix { get; set; } + /// The FQDN of the Fleet hub. + string HubProfileFqdn { get; set; } + /// The Kubernetes version of the Fleet hub. + string HubProfileKubernetesVersion { get; set; } + /// The Azure Portal FQDN of the Fleet hub. + string HubProfilePortalFqdn { get; set; } + /// The error additional info. + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; set; } + /// The error code. + string LastOperationErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastOperationErrorDetail { get; set; } + /// The error message. + string LastOperationErrorMessage { get; set; } + /// The error target. + string LastOperationErrorTarget { get; set; } + /// The status of the last operation. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting")] + string ProvisioningState { get; set; } + /// Status information for the fleet. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus Status { get; set; } + /// The last operation error for the fleet. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusLastOperationError { get; set; } + /// The last operation ID for the fleet. + string StatusLastOperationId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.json.cs new file mode 100644 index 00000000000..1939f16b31f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Fleet properties. + public partial class FleetProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_hubProfile = If( json?.PropertyT("hubProfile"), out var __jsonHubProfile) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetHubProfile.FromJson(__jsonHubProfile) : _hubProfile;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetStatus.FromJson(__jsonStatus) : _status;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._hubProfile ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._hubProfile.ToJson(null,serializationMode) : null, "hubProfile" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/FleetStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.PowerShell.cs new file mode 100644 index 00000000000..f83f6423944 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Status information for the fleet. + [System.ComponentModel.TypeConverter(typeof(FleetStatusTypeConverter))] + public partial class FleetStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetStatus(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("LastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("LastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("LastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationId = (string) content.GetValueForProperty("LastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("LastOperationError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("LastOperationError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("LastOperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationId = (string) content.GetValueForProperty("LastOperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationId, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorCode = (string) content.GetValueForProperty("LastOperationErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorCode, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorMessage = (string) content.GetValueForProperty("LastOperationErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorTarget = (string) content.GetValueForProperty("LastOperationErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("LastOperationErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("LastOperationErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("LastOperationErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal)this).LastOperationErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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(); + } + } + /// Status information for the fleet. + [System.ComponentModel.TypeConverter(typeof(FleetStatusTypeConverter))] + public partial interface IFleetStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.TypeConverter.cs new file mode 100644 index 00000000000..134aca5544c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.cs new file mode 100644 index 00000000000..b66b0bbdcb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Status information for the fleet. + public partial class FleetStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail _lastOperationError; + + /// The last operation error for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail LastOperationError { get => (this._lastOperationError = this._lastOperationError ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Message; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Target; } + + /// Backing field for property. + private string _lastOperationId; + + /// The last operation ID for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string LastOperationId { get => this._lastOperationId; } + + /// Internal Acessors for LastOperationError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationError { get => (this._lastOperationError = this._lastOperationError ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); set { {_lastOperationError = value;} } } + + /// Internal Acessors for LastOperationErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Code = value ?? null; } + + /// Internal Acessors for LastOperationErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for LastOperationErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Message = value ?? null; } + + /// Internal Acessors for LastOperationErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)LastOperationError).Target = value ?? null; } + + /// Internal Acessors for LastOperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatusInternal.LastOperationId { get => this._lastOperationId; set { {_lastOperationId = value;} } } + + /// Creates an new instance. + public FleetStatus() + { + + } + } + /// Status information for the fleet. + public partial interface IFleetStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List LastOperationErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string LastOperationErrorTarget { get; } + /// The last operation ID for the fleet. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The last operation ID for the fleet.", + SerializedName = @"lastOperationId", + PossibleTypes = new [] { typeof(string) })] + string LastOperationId { get; } + + } + /// Status information for the fleet. + internal partial interface IFleetStatusInternal + + { + /// The last operation error for the fleet. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail LastOperationError { get; set; } + /// The error additional info. + System.Collections.Generic.List LastOperationErrorAdditionalInfo { get; set; } + /// The error code. + string LastOperationErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List LastOperationErrorDetail { get; set; } + /// The error message. + string LastOperationErrorMessage { get; set; } + /// The error target. + string LastOperationErrorTarget { get; set; } + /// The last operation ID for the fleet. + string LastOperationId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.json.cs new file mode 100644 index 00000000000..43f73d034a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetStatus.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Status information for the fleet. + public partial class FleetStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_lastOperationError = If( json?.PropertyT("lastOperationError"), out var __jsonLastOperationError) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail.FromJson(__jsonLastOperationError) : _lastOperationError;} + {_lastOperationId = If( json?.PropertyT("lastOperationId"), out var __jsonLastOperationId) ? (string)__jsonLastOperationId : (string)_lastOperationId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastOperationError ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._lastOperationError.ToJson(null,serializationMode) : null, "lastOperationError" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._lastOperationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._lastOperationId.ToString()) : null, "lastOperationId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.PowerShell.cs new file mode 100644 index 00000000000..22b1d8c53e1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.PowerShell.cs @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + [System.ComponentModel.TypeConverter(typeof(FleetUpdateStrategyTypeConverter))] + public partial class FleetUpdateStrategy + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetUpdateStrategy DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetUpdateStrategy(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetUpdateStrategy(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetUpdateStrategy(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.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetUpdateStrategy(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.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.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.ContainerServiceFleet.Models.IFleetUpdateStrategy FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 a multi-stage process to perform update operations across members of a Fleet. + [System.ComponentModel.TypeConverter(typeof(FleetUpdateStrategyTypeConverter))] + public partial interface IFleetUpdateStrategy + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.TypeConverter.cs new file mode 100644 index 00000000000..a7c40ac3871 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetUpdateStrategyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetUpdateStrategy ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetUpdateStrategy.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetUpdateStrategy.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetUpdateStrategy.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.cs new file mode 100644 index 00000000000..396a9fa33ad --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.cs @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + public partial class FleetUpdateStrategy : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(); + + /// Backing field for property. + private string _eTag; + + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Strategy + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyInternal.Strategy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).Strategy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).Strategy = value ?? null /* model class */; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyProperties()); set => this._property = value; } + + /// The provisioning state of the UpdateStrategy resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StrategyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).StrategyStage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)Property).StrategyStage = value ?? null /* arrayOf */; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public FleetUpdateStrategy() + { + + } + + /// 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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Defines a multi-stage process to perform update operations across members of a Fleet. + public partial interface IFleetUpdateStrategy : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource + { + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// The provisioning state of the UpdateStrategy resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the UpdateStrategy resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + System.Collections.Generic.List StrategyStage { get; set; } + + } + /// Defines a multi-stage process to perform update operations across members of a Fleet. + internal partial interface IFleetUpdateStrategyInternal : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResourceInternal + { + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + string ETag { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties Property { get; set; } + /// The provisioning state of the UpdateStrategy resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// Defines the update sequence of the clusters. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Strategy { get; set; } + /// The list of stages that compose this update run. Min size: 1. + System.Collections.Generic.List StrategyStage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.json.cs new file mode 100644 index 00000000000..cc70d468a75 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategy.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + public partial class FleetUpdateStrategy + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetUpdateStrategy(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyProperties.FromJson(__jsonProperties) : _property;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)_eTag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetUpdateStrategy(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.PowerShell.cs new file mode 100644 index 00000000000..7d58a378c85 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The response of a FleetUpdateStrategy list operation. + [System.ComponentModel.TypeConverter(typeof(FleetUpdateStrategyListResultTypeConverter))] + public partial class FleetUpdateStrategyListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetUpdateStrategyListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetUpdateStrategyListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetUpdateStrategyListResult(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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)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 FleetUpdateStrategyListResult(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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategyTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal)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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 FleetUpdateStrategy list operation. + [System.ComponentModel.TypeConverter(typeof(FleetUpdateStrategyListResultTypeConverter))] + public partial interface IFleetUpdateStrategyListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.TypeConverter.cs new file mode 100644 index 00000000000..4a9290f287e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetUpdateStrategyListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetUpdateStrategyListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetUpdateStrategyListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetUpdateStrategyListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.cs new file mode 100644 index 00000000000..c17ef5c8bbd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a FleetUpdateStrategy list operation. + public partial class FleetUpdateStrategyListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The FleetUpdateStrategy items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public FleetUpdateStrategyListResult() + { + + } + } + /// The response of a FleetUpdateStrategy list operation. + public partial interface IFleetUpdateStrategyListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 FleetUpdateStrategy items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The FleetUpdateStrategy items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a FleetUpdateStrategy list operation. + internal partial interface IFleetUpdateStrategyListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The FleetUpdateStrategy items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.json.cs new file mode 100644 index 00000000000..1f5c3d2e886 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a FleetUpdateStrategy list operation. + public partial class FleetUpdateStrategyListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetUpdateStrategyListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy.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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetUpdateStrategyListResult(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.PowerShell.cs new file mode 100644 index 00000000000..17e414ff4ce --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The properties of the UpdateStrategy. + [System.ComponentModel.TypeConverter(typeof(FleetUpdateStrategyPropertiesTypeConverter))] + public partial class FleetUpdateStrategyProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FleetUpdateStrategyProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FleetUpdateStrategyProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FleetUpdateStrategyProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FleetUpdateStrategyProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.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.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 properties of the UpdateStrategy. + [System.ComponentModel.TypeConverter(typeof(FleetUpdateStrategyPropertiesTypeConverter))] + public partial interface IFleetUpdateStrategyProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.TypeConverter.cs new file mode 100644 index 00000000000..6d4cb0dab16 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FleetUpdateStrategyPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FleetUpdateStrategyProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FleetUpdateStrategyProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FleetUpdateStrategyProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.cs new file mode 100644 index 00000000000..ddd0cd0eb81 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the UpdateStrategy. + public partial class FleetUpdateStrategyProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal + { + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for Strategy + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyPropertiesInternal.Strategy { get => (this._strategy = this._strategy ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategy()); set { {_strategy = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state of the UpdateStrategy resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy _strategy; + + /// Defines the update sequence of the clusters. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Strategy { get => (this._strategy = this._strategy ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategy()); set => this._strategy = value; } + + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StrategyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)Strategy).Stage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)Strategy).Stage = value ; } + + /// Creates an new instance. + public FleetUpdateStrategyProperties() + { + + } + } + /// The properties of the UpdateStrategy. + public partial interface IFleetUpdateStrategyProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The provisioning state of the UpdateStrategy resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the UpdateStrategy resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + System.Collections.Generic.List StrategyStage { get; set; } + + } + /// The properties of the UpdateStrategy. + internal partial interface IFleetUpdateStrategyPropertiesInternal + + { + /// The provisioning state of the UpdateStrategy resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// Defines the update sequence of the clusters. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Strategy { get; set; } + /// The list of stages that compose this update run. Min size: 1. + System.Collections.Generic.List StrategyStage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.json.cs new file mode 100644 index 00000000000..dffcdb5ca14 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/FleetUpdateStrategyProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the UpdateStrategy. + public partial class FleetUpdateStrategyProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal FleetUpdateStrategyProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_strategy = If( json?.PropertyT("strategy"), out var __jsonStrategy) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategy.FromJson(__jsonStrategy) : _strategy;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategyProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new FleetUpdateStrategyProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._strategy ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._strategy.ToJson(null,serializationMode) : null, "strategy" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Gate.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.PowerShell.cs new file mode 100644 index 00000000000..59cfafb3848 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.PowerShell.cs @@ -0,0 +1,338 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + [System.ComponentModel.TypeConverter(typeof(GateTypeConverter))] + public partial class Gate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Gate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Gate(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Gate(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.ContainerServiceFleet.Models.IGateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("GateType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).GateType = (string) content.GetValueForProperty("GateType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).GateType, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).Target = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).Target, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTargetTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("TargetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetId = (string) content.GetValueForProperty("TargetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetId, global::System.Convert.ToString); + } + if (content.Contains("TargetUpdateRunProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetUpdateRunProperty = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties) content.GetValueForProperty("TargetUpdateRunProperty",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetUpdateRunProperty, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("UpdateRunPropertyTiming")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyTiming = (string) content.GetValueForProperty("UpdateRunPropertyTiming",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyTiming, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyName = (string) content.GetValueForProperty("UpdateRunPropertyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyStage = (string) content.GetValueForProperty("UpdateRunPropertyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyStage, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyGroup = (string) content.GetValueForProperty("UpdateRunPropertyGroup",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyGroup, 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 Gate(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.ContainerServiceFleet.Models.IGateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("GateType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).GateType = (string) content.GetValueForProperty("GateType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).GateType, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).Target = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).Target, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTargetTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("TargetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetId = (string) content.GetValueForProperty("TargetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetId, global::System.Convert.ToString); + } + if (content.Contains("TargetUpdateRunProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetUpdateRunProperty = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties) content.GetValueForProperty("TargetUpdateRunProperty",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).TargetUpdateRunProperty, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("UpdateRunPropertyTiming")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyTiming = (string) content.GetValueForProperty("UpdateRunPropertyTiming",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyTiming, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyName = (string) content.GetValueForProperty("UpdateRunPropertyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyStage = (string) content.GetValueForProperty("UpdateRunPropertyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyStage, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyGroup = (string) content.GetValueForProperty("UpdateRunPropertyGroup",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal)this).UpdateRunPropertyGroup, 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.ContainerServiceFleet.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 Gate controls the progression during a staged rollout, e.g. in an Update Run. + [System.ComponentModel.TypeConverter(typeof(GateTypeConverter))] + public partial interface IGate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.TypeConverter.cs new file mode 100644 index 00000000000..3b3e8447d8c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Gate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Gate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Gate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/Gate.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.cs new file mode 100644 index 00000000000..7c18e512377 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.cs @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + public partial class Gate : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(); + + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string DisplayName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).DisplayName; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).DisplayName = value ?? null; } + + /// Backing field for property. + private string _eTag; + + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// The type of the Gate determines how it is completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string GateType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).GateType; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for GateType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.GateType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).GateType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).GateType = value ?? null; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Target + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).Target = value ?? null /* model class */; } + + /// Internal Acessors for TargetUpdateRunProperty + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.TargetUpdateRunProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).TargetUpdateRunProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).TargetUpdateRunProperty = value ?? null /* model class */; } + + /// Internal Acessors for UpdateRunPropertyGroup + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.UpdateRunPropertyGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyGroup; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyGroup = value ?? null; } + + /// Internal Acessors for UpdateRunPropertyName + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.UpdateRunPropertyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyName; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyName = value ?? null; } + + /// Internal Acessors for UpdateRunPropertyStage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateInternal.UpdateRunPropertyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyStage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyStage = value ?? null; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateProperties()); set => this._property = value; } + + /// The provisioning state of the Gate resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string State { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).State = value ?? null; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// The resource id that the Gate is controlling the rollout of. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string TargetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).TargetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).TargetId = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; } + + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyGroup; } + + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyName; } + + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyStage; } + + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyTiming { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyTiming; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)Property).UpdateRunPropertyTiming = value ?? null; } + + /// Creates an new instance. + public Gate() + { + + } + + /// 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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + public partial interface IGate : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource + { + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The human-readable display name of the Gate.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// The type of the Gate determines how it is completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = true, + Update = false, + Description = @"The type of the Gate determines how it is completed.", + SerializedName = @"gateType", + PossibleTypes = new [] { typeof(string) })] + string GateType { get; } + /// The provisioning state of the Gate resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the Gate resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + /// The resource id that the Gate is controlling the rollout of. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The resource id that the Gate is controlling the rollout of.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string TargetId { get; set; } + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Group of the Update Run.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyGroup { get; } + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the Update Run.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyName { get; } + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Stage of the Update Run.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyStage { get; } + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether the Gate is placed before or after the update itself.", + SerializedName = @"timing", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string UpdateRunPropertyTiming { get; set; } + + } + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + internal partial interface IGateInternal : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResourceInternal + { + /// The human-readable display name of the Gate. + string DisplayName { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + string ETag { get; set; } + /// The type of the Gate determines how it is completed. + string GateType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties Property { get; set; } + /// The provisioning state of the Gate resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// The state of the Gate. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + /// The target that the Gate is controlling, e.g. an Update Run. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget Target { get; set; } + /// The resource id that the Gate is controlling the rollout of. + string TargetId { get; set; } + /// The properties of the Update Run that the Gate is targeting. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties TargetUpdateRunProperty { get; set; } + /// The Update Group of the Update Run. + string UpdateRunPropertyGroup { get; set; } + /// The name of the Update Run. + string UpdateRunPropertyName { get; set; } + /// The Update Stage of the Update Run. + string UpdateRunPropertyStage { get; set; } + /// Whether the Gate is placed before or after the update itself. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string UpdateRunPropertyTiming { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.json.cs new file mode 100644 index 00000000000..dad3049af4f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Gate.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + public partial class Gate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new Gate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal Gate(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateProperties.FromJson(__jsonProperties) : _property;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)_eTag;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.PowerShell.cs new file mode 100644 index 00000000000..f2d03a30dfc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// GateConfiguration is used to define where Gates should be placed within the Update Run. + /// + [System.ComponentModel.TypeConverter(typeof(GateConfigurationTypeConverter))] + public partial class GateConfiguration + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGateConfiguration DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GateConfiguration(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GateConfiguration(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GateConfiguration(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)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 GateConfiguration(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal)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.ContainerServiceFleet.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(); + } + } + /// GateConfiguration is used to define where Gates should be placed within the Update Run. + [System.ComponentModel.TypeConverter(typeof(GateConfigurationTypeConverter))] + public partial interface IGateConfiguration + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.TypeConverter.cs new file mode 100644 index 00000000000..55d9c7ab8da --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GateConfigurationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGateConfiguration ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GateConfiguration.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GateConfiguration.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GateConfiguration.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.cs new file mode 100644 index 00000000000..fdbd29bd5fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// GateConfiguration is used to define where Gates should be placed within the Update Run. + /// + public partial class GateConfiguration : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal + { + + /// Backing field for property. + private string _displayName; + + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; set => this._displayName = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfigurationInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type= @"Approval"; + + /// The type of the Gate determines how it is completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public GateConfiguration() + { + + } + } + /// GateConfiguration is used to define where Gates should be placed within the Update Run. + public partial interface IGateConfiguration : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The human-readable display name of the Gate.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; set; } + /// The type of the Gate determines how it is completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = true, + Read = true, + Create = true, + Update = true, + Description = @"The type of the Gate determines how it is completed.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// GateConfiguration is used to define where Gates should be placed within the Update Run. + internal partial interface IGateConfigurationInternal + + { + /// The human-readable display name of the Gate. + string DisplayName { get; set; } + /// The type of the Gate determines how it is completed. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.json.cs new file mode 100644 index 00000000000..d1ccb77233c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateConfiguration.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// GateConfiguration is used to define where Gates should be placed within the Update Run. + /// + public partial class GateConfiguration + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GateConfiguration(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GateConfiguration(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/GateListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.PowerShell.cs new file mode 100644 index 00000000000..405050b78d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The response of a Gate list operation. + [System.ComponentModel.TypeConverter(typeof(GateListResultTypeConverter))] + public partial class GateListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGateListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GateListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GateListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GateListResult(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.ContainerServiceFleet.Models.IGateListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal)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 GateListResult(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.ContainerServiceFleet.Models.IGateListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal)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.ContainerServiceFleet.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 Gate list operation. + [System.ComponentModel.TypeConverter(typeof(GateListResultTypeConverter))] + public partial interface IGateListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.TypeConverter.cs new file mode 100644 index 00000000000..7b1509338bd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GateListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGateListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GateListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GateListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GateListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GateListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.cs new file mode 100644 index 00000000000..60d76517468 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a Gate list operation. + public partial class GateListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Gate items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public GateListResult() + { + + } + } + /// The response of a Gate list operation. + public partial interface IGateListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 Gate items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Gate items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a Gate list operation. + internal partial interface IGateListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Gate items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.json.cs new file mode 100644 index 00000000000..207e16154b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a Gate list operation. + public partial class GateListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GateListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GateListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Gate.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/GatePatch.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.PowerShell.cs new file mode 100644 index 00000000000..38f5abe79f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Patch a Gate resource. + [System.ComponentModel.TypeConverter(typeof(GatePatchTypeConverter))] + public partial class GatePatch + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGatePatch DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GatePatch(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GatePatch(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GatePatch(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.ContainerServiceFleet.Models.IGatePatchInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatchPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal)this).State, 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 GatePatch(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.ContainerServiceFleet.Models.IGatePatchInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatchPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal)this).State, 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.ContainerServiceFleet.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(); + } + } + /// Patch a Gate resource. + [System.ComponentModel.TypeConverter(typeof(GatePatchTypeConverter))] + public partial interface IGatePatch + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.TypeConverter.cs new file mode 100644 index 00000000000..84474ee6d4c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GatePatchTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGatePatch ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GatePatch.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GatePatch.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GatePatch.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GatePatch.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.cs new file mode 100644 index 00000000000..aa397b789d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Patch a Gate resource. + public partial class GatePatch : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal + { + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatchProperties()); set { {_property = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties _property; + + /// Properties of a Gate that can be patched. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatchProperties()); set => this._property = value; } + + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string State { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal)Property).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal)Property).State = value ; } + + /// Creates an new instance. + public GatePatch() + { + + } + } + /// Patch a Gate resource. + public partial interface IGatePatch : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + + } + /// Patch a Gate resource. + internal partial interface IGatePatchInternal + + { + /// Properties of a Gate that can be patched. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties Property { get; set; } + /// The state of the Gate. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.json.cs new file mode 100644 index 00000000000..42f59586ea6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatch.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Patch a Gate resource. + public partial class GatePatch + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GatePatch(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GatePatch(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.GatePatchProperties.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.PowerShell.cs new file mode 100644 index 00000000000..7c74e065e8e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Properties of a Gate that can be patched. + [System.ComponentModel.TypeConverter(typeof(GatePatchPropertiesTypeConverter))] + public partial class GatePatchProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGatePatchProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GatePatchProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GatePatchProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GatePatchProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal)this).State, 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 GatePatchProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal)this).State, 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.ContainerServiceFleet.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 a Gate that can be patched. + [System.ComponentModel.TypeConverter(typeof(GatePatchPropertiesTypeConverter))] + public partial interface IGatePatchProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.TypeConverter.cs new file mode 100644 index 00000000000..a113bae7e7b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GatePatchPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGatePatchProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GatePatchProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GatePatchProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GatePatchProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.cs new file mode 100644 index 00000000000..d4a5cdb6d3d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Properties of a Gate that can be patched. + public partial class GatePatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchPropertiesInternal + { + + /// Backing field for property. + private string _state; + + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string State { get => this._state; set => this._state = value; } + + /// Creates an new instance. + public GatePatchProperties() + { + + } + } + /// Properties of a Gate that can be patched. + public partial interface IGatePatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + + } + /// Properties of a Gate that can be patched. + internal partial interface IGatePatchPropertiesInternal + + { + /// The state of the Gate. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.json.cs new file mode 100644 index 00000000000..923e4a7ff34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GatePatchProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Properties of a Gate that can be patched. + public partial class GatePatchProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatchProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GatePatchProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GatePatchProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.PowerShell.cs new file mode 100644 index 00000000000..8d5a1b6f218 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + [System.ComponentModel.TypeConverter(typeof(GatePropertiesTypeConverter))] + public partial class GateProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGateProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GateProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GateProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GateProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).Target = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).Target, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTargetTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("GateType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).GateType = (string) content.GetValueForProperty("GateType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).GateType, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("TargetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetId = (string) content.GetValueForProperty("TargetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetId, global::System.Convert.ToString); + } + if (content.Contains("TargetUpdateRunProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetUpdateRunProperty = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties) content.GetValueForProperty("TargetUpdateRunProperty",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetUpdateRunProperty, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("UpdateRunPropertyTiming")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyTiming = (string) content.GetValueForProperty("UpdateRunPropertyTiming",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyTiming, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyName = (string) content.GetValueForProperty("UpdateRunPropertyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyStage = (string) content.GetValueForProperty("UpdateRunPropertyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyStage, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyGroup = (string) content.GetValueForProperty("UpdateRunPropertyGroup",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyGroup, 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 GateProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).Target = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).Target, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTargetTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("GateType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).GateType = (string) content.GetValueForProperty("GateType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).GateType, global::System.Convert.ToString); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("TargetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetId = (string) content.GetValueForProperty("TargetId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetId, global::System.Convert.ToString); + } + if (content.Contains("TargetUpdateRunProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetUpdateRunProperty = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties) content.GetValueForProperty("TargetUpdateRunProperty",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).TargetUpdateRunProperty, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("UpdateRunPropertyTiming")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyTiming = (string) content.GetValueForProperty("UpdateRunPropertyTiming",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyTiming, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyName = (string) content.GetValueForProperty("UpdateRunPropertyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyStage = (string) content.GetValueForProperty("UpdateRunPropertyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyStage, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyGroup = (string) content.GetValueForProperty("UpdateRunPropertyGroup",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal)this).UpdateRunPropertyGroup, 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.ContainerServiceFleet.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 Gate controls the progression during a staged rollout, e.g. in an Update Run. + [System.ComponentModel.TypeConverter(typeof(GatePropertiesTypeConverter))] + public partial interface IGateProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.TypeConverter.cs new file mode 100644 index 00000000000..57e8b6f0062 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GatePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGateProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GateProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GateProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GateProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GateProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.cs new file mode 100644 index 00000000000..1d5a145fec1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.cs @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + public partial class GateProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal + { + + /// Backing field for property. + private string _displayName; + + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; set => this._displayName = value; } + + /// Backing field for property. + private string _gateType= @"Approval"; + + /// The type of the Gate determines how it is completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string GateType { get => this._gateType; } + + /// Internal Acessors for GateType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.GateType { get => this._gateType; set { {_gateType = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for Target + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.Target { get => (this._target = this._target ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTarget()); set { {_target = value;} } } + + /// Internal Acessors for TargetUpdateRunProperty + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.TargetUpdateRunProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunProperty = value ?? null /* model class */; } + + /// Internal Acessors for UpdateRunPropertyGroup + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.UpdateRunPropertyGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyGroup; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyGroup = value ?? null; } + + /// Internal Acessors for UpdateRunPropertyName + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.UpdateRunPropertyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyName; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyName = value ?? null; } + + /// Internal Acessors for UpdateRunPropertyStage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePropertiesInternal.UpdateRunPropertyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyStage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyStage = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state of the Gate resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _state; + + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string State { get => this._state; set => this._state = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget _target; + + /// The target that the Gate is controlling, e.g. an Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget Target { get => (this._target = this._target ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTarget()); set => this._target = value; } + + /// The resource id that the Gate is controlling the rollout of. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string TargetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).Id = value ?? null; } + + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyGroup; } + + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyName; } + + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyStage; } + + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyTiming { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyTiming; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)Target).UpdateRunPropertyTiming = value ?? null; } + + /// Creates an new instance. + public GateProperties() + { + + } + } + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + public partial interface IGateProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The human-readable display name of the Gate.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; set; } + /// The type of the Gate determines how it is completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = true, + Update = false, + Description = @"The type of the Gate determines how it is completed.", + SerializedName = @"gateType", + PossibleTypes = new [] { typeof(string) })] + string GateType { get; } + /// The provisioning state of the Gate resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the Gate resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The state of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + /// The resource id that the Gate is controlling the rollout of. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The resource id that the Gate is controlling the rollout of.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string TargetId { get; set; } + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Group of the Update Run.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyGroup { get; } + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the Update Run.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyName { get; } + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Stage of the Update Run.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyStage { get; } + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether the Gate is placed before or after the update itself.", + SerializedName = @"timing", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string UpdateRunPropertyTiming { get; set; } + + } + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + internal partial interface IGatePropertiesInternal + + { + /// The human-readable display name of the Gate. + string DisplayName { get; set; } + /// The type of the Gate determines how it is completed. + string GateType { get; set; } + /// The provisioning state of the Gate resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// The state of the Gate. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + string State { get; set; } + /// The target that the Gate is controlling, e.g. an Update Run. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget Target { get; set; } + /// The resource id that the Gate is controlling the rollout of. + string TargetId { get; set; } + /// The properties of the Update Run that the Gate is targeting. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties TargetUpdateRunProperty { get; set; } + /// The Update Group of the Update Run. + string UpdateRunPropertyGroup { get; set; } + /// The name of the Update Run. + string UpdateRunPropertyName { get; set; } + /// The Update Stage of the Update Run. + string UpdateRunPropertyStage { get; set; } + /// Whether the Gate is placed before or after the update itself. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string UpdateRunPropertyTiming { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.json.cs new file mode 100644 index 00000000000..850badf9a3f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A Gate controls the progression during a staged rollout, e.g. in an Update Run. + public partial class GateProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GateProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GateProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_target = If( json?.PropertyT("target"), out var __jsonTarget) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateTarget.FromJson(__jsonTarget) : _target;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_gateType = If( json?.PropertyT("gateType"), out var __jsonGateType) ? (string)__jsonGateType : (string)_gateType;} + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._target ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._target.ToJson(null,serializationMode) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._gateType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._gateType.ToString()) : null, "gateType" ,container.Add ); + } + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.PowerShell.cs new file mode 100644 index 00000000000..ddd6bbc8601 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// The target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set. + /// + [System.ComponentModel.TypeConverter(typeof(GateTargetTypeConverter))] + public partial class GateTarget + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGateTarget DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GateTarget(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GateTarget(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GateTarget(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("UpdateRunProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunProperty = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties) content.GetValueForProperty("UpdateRunProperty",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunProperty, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyTiming")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyTiming = (string) content.GetValueForProperty("UpdateRunPropertyTiming",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyTiming, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyName = (string) content.GetValueForProperty("UpdateRunPropertyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyStage = (string) content.GetValueForProperty("UpdateRunPropertyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyStage, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyGroup = (string) content.GetValueForProperty("UpdateRunPropertyGroup",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyGroup, 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 GateTarget(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("UpdateRunProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunProperty = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties) content.GetValueForProperty("UpdateRunProperty",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunProperty, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyTiming")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyTiming = (string) content.GetValueForProperty("UpdateRunPropertyTiming",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyTiming, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyName = (string) content.GetValueForProperty("UpdateRunPropertyName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyName, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyStage = (string) content.GetValueForProperty("UpdateRunPropertyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyStage, global::System.Convert.ToString); + } + if (content.Contains("UpdateRunPropertyGroup")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyGroup = (string) content.GetValueForProperty("UpdateRunPropertyGroup",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal)this).UpdateRunPropertyGroup, 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.ContainerServiceFleet.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 target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set. + [System.ComponentModel.TypeConverter(typeof(GateTargetTypeConverter))] + public partial interface IGateTarget + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.TypeConverter.cs new file mode 100644 index 00000000000..c8ddffc8d61 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GateTargetTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGateTarget ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GateTarget.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GateTarget.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GateTarget.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GateTarget.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.cs new file mode 100644 index 00000000000..db2be0ef110 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// The target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set. + /// + public partial class GateTarget : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal + { + + /// Backing field for property. + private string _id; + + /// The resource id that the Gate is controlling the rollout of. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Internal Acessors for UpdateRunProperty + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal.UpdateRunProperty { get => (this._updateRunProperty = this._updateRunProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetProperties()); set { {_updateRunProperty = value;} } } + + /// Internal Acessors for UpdateRunPropertyGroup + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal.UpdateRunPropertyGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Group; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Group = value ?? null; } + + /// Internal Acessors for UpdateRunPropertyName + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal.UpdateRunPropertyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Name = value ?? null; } + + /// Internal Acessors for UpdateRunPropertyStage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTargetInternal.UpdateRunPropertyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Stage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Stage = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties _updateRunProperty; + + /// The properties of the Update Run that the Gate is targeting. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties UpdateRunProperty { get => (this._updateRunProperty = this._updateRunProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetProperties()); set => this._updateRunProperty = value; } + + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Group; } + + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Name; } + + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Stage; } + + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateRunPropertyTiming { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Timing; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)UpdateRunProperty).Timing = value ?? null; } + + /// Creates an new instance. + public GateTarget() + { + + } + } + /// The target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set. + public partial interface IGateTarget : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The resource id that the Gate is controlling the rollout of. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The resource id that the Gate is controlling the rollout of.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Group of the Update Run.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyGroup { get; } + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the Update Run.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyName { get; } + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Stage of the Update Run.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + string UpdateRunPropertyStage { get; } + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether the Gate is placed before or after the update itself.", + SerializedName = @"timing", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string UpdateRunPropertyTiming { get; set; } + + } + /// The target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set. + internal partial interface IGateTargetInternal + + { + /// The resource id that the Gate is controlling the rollout of. + string Id { get; set; } + /// The properties of the Update Run that the Gate is targeting. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties UpdateRunProperty { get; set; } + /// The Update Group of the Update Run. + string UpdateRunPropertyGroup { get; set; } + /// The name of the Update Run. + string UpdateRunPropertyName { get; set; } + /// The Update Stage of the Update Run. + string UpdateRunPropertyStage { get; set; } + /// Whether the Gate is placed before or after the update itself. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string UpdateRunPropertyTiming { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.json.cs new file mode 100644 index 00000000000..e177c1485a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GateTarget.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// The target that the Gate is controlling, e.g. an Update Run. Exactly one of the properties objects will be set. + /// + public partial class GateTarget + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateTarget FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GateTarget(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GateTarget(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_updateRunProperty = If( json?.PropertyT("updateRunProperties"), out var __jsonUpdateRunProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateTargetProperties.FromJson(__jsonUpdateRunProperties) : _updateRunProperty;} + {_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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._updateRunProperty ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._updateRunProperty.ToJson(null,serializationMode) : null, "updateRunProperties" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.PowerShell.cs new file mode 100644 index 00000000000..07dc9703bbb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// GenerateResponse is the response of a generate request. + [System.ComponentModel.TypeConverter(typeof(GenerateResponseTypeConverter))] + public partial class GenerateResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IGenerateResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new GenerateResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new GenerateResponse(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal GenerateResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponseInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponseInternal)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 GenerateResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponseInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponseInternal)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.ContainerServiceFleet.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(); + } + } + /// GenerateResponse is the response of a generate request. + [System.ComponentModel.TypeConverter(typeof(GenerateResponseTypeConverter))] + public partial interface IGenerateResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.TypeConverter.cs new file mode 100644 index 00000000000..72a18d0ee0c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class GenerateResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IGenerateResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return GenerateResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return GenerateResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return GenerateResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.cs new file mode 100644 index 00000000000..fd50c63b555 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// GenerateResponse is the response of a generate request. + public partial class GenerateResponse : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponseInternal + { + + /// Backing field for property. + private string _id; + + /// + /// The ARM resource id of the generated UpdateRun. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponseInternal.Id { get => this._id; set { {_id = value;} } } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// Creates an new instance. + public GenerateResponse() + { + + } + } + /// GenerateResponse is the response of a generate request. + public partial interface IGenerateResponse : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The ARM resource id of the generated UpdateRun. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The ARM resource id of the generated UpdateRun. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + + } + /// GenerateResponse is the response of a generate request. + internal partial interface IGenerateResponseInternal + + { + /// + /// The ARM resource id of the generated UpdateRun. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'. + /// + string Id { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.json.cs new file mode 100644 index 00000000000..0715fc94b39 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/GenerateResponse.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// GenerateResponse is the response of a generate request. + public partial class GenerateResponse + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new GenerateResponse(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal GenerateResponse(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.PowerShell.cs new file mode 100644 index 00000000000..2c39eb6d371 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The update to be applied to the ManagedClusters. + [System.ComponentModel.TypeConverter(typeof(ManagedClusterUpdateTypeConverter))] + public partial class ManagedClusterUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IManagedClusterUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedClusterUpdate(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedClusterUpdate(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedClusterUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Upgrade")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).Upgrade = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec) content.GetValueForProperty("Upgrade",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).Upgrade, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpecTypeConverter.ConvertFrom); + } + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("UpgradeKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeKubernetesVersion = (string) content.GetValueForProperty("UpgradeKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("UpgradeType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeType = (string) content.GetValueForProperty("UpgradeType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeType, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionCustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionCustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionCustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionCustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedClusterUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Upgrade")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).Upgrade = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec) content.GetValueForProperty("Upgrade",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).Upgrade, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpecTypeConverter.ConvertFrom); + } + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("UpgradeKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeKubernetesVersion = (string) content.GetValueForProperty("UpgradeKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("UpgradeType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeType = (string) content.GetValueForProperty("UpgradeType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).UpgradeType, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionCustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionCustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionCustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)this).NodeImageSelectionCustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.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.ContainerServiceFleet.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 update to be applied to the ManagedClusters. + [System.ComponentModel.TypeConverter(typeof(ManagedClusterUpdateTypeConverter))] + public partial interface IManagedClusterUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.TypeConverter.cs new file mode 100644 index 00000000000..c9e01c7d3bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedClusterUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IManagedClusterUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedClusterUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedClusterUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedClusterUpdate.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.cs new file mode 100644 index 00000000000..a483e70a1f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The update to be applied to the ManagedClusters. + public partial class ManagedClusterUpdate : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal + { + + /// Internal Acessors for NodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal.NodeImageSelection { get => (this._nodeImageSelection = this._nodeImageSelection ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelection()); set { {_nodeImageSelection = value;} } } + + /// Internal Acessors for Upgrade + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal.Upgrade { get => (this._upgrade = this._upgrade ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpec()); set { {_upgrade = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection _nodeImageSelection; + + /// The node image upgrade to be applied to the target nodes in update run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection NodeImageSelection { get => (this._nodeImageSelection = this._nodeImageSelection ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelection()); set => this._nodeImageSelection = value; } + + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)NodeImageSelection).CustomNodeImageVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)NodeImageSelection).CustomNodeImageVersion = value ?? null /* arrayOf */; } + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string NodeImageSelectionType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)NodeImageSelection).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)NodeImageSelection).Type = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec _upgrade; + + /// The upgrade to apply to the ManagedClusters. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec Upgrade { get => (this._upgrade = this._upgrade ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpec()); set => this._upgrade = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpgradeKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)Upgrade).KubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)Upgrade).KubernetesVersion = value ?? null; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpgradeType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)Upgrade).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)Upgrade).Type = value ; } + + /// Creates an new instance. + public ManagedClusterUpdate() + { + + } + } + /// The update to be applied to the ManagedClusters. + public partial interface IManagedClusterUpdate : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.", + SerializedName = @"customNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get; set; } + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string NodeImageSelectionType { get; set; } + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string UpgradeKubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string UpgradeType { get; set; } + + } + /// The update to be applied to the ManagedClusters. + internal partial interface IManagedClusterUpdateInternal + + { + /// The node image upgrade to be applied to the target nodes in update run. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection NodeImageSelection { get; set; } + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get; set; } + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string NodeImageSelectionType { get; set; } + /// The upgrade to apply to the ManagedClusters. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec Upgrade { get; set; } + /// The Kubernetes version to upgrade the member clusters to. + string UpgradeKubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string UpgradeType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.json.cs new file mode 100644 index 00000000000..a910d7151c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpdate.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The update to be applied to the ManagedClusters. + public partial class ManagedClusterUpdate + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ManagedClusterUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedClusterUpdate(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_upgrade = If( json?.PropertyT("upgrade"), out var __jsonUpgrade) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpec.FromJson(__jsonUpgrade) : _upgrade;} + {_nodeImageSelection = If( json?.PropertyT("nodeImageSelection"), out var __jsonNodeImageSelection) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelection.FromJson(__jsonNodeImageSelection) : _nodeImageSelection;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._upgrade ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._upgrade.ToJson(null,serializationMode) : null, "upgrade" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._nodeImageSelection ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._nodeImageSelection.ToJson(null,serializationMode) : null, "nodeImageSelection" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.PowerShell.cs new file mode 100644 index 00000000000..60f55b19f60 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The upgrade to apply to a ManagedCluster. + [System.ComponentModel.TypeConverter(typeof(ManagedClusterUpgradeSpecTypeConverter))] + public partial class ManagedClusterUpgradeSpec + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedClusterUpgradeSpec(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedClusterUpgradeSpec(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedClusterUpgradeSpec(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.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("KubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).KubernetesVersion, 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 ManagedClusterUpgradeSpec(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.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("KubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal)this).KubernetesVersion, 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.ContainerServiceFleet.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 upgrade to apply to a ManagedCluster. + [System.ComponentModel.TypeConverter(typeof(ManagedClusterUpgradeSpecTypeConverter))] + public partial interface IManagedClusterUpgradeSpec + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.TypeConverter.cs new file mode 100644 index 00000000000..20a13bafee3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedClusterUpgradeSpecTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedClusterUpgradeSpec.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedClusterUpgradeSpec.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedClusterUpgradeSpec.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.cs new file mode 100644 index 00000000000..a438cf25cdb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The upgrade to apply to a ManagedCluster. + public partial class ManagedClusterUpgradeSpec : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpecInternal + { + + /// Backing field for property. + private string _kubernetesVersion; + + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string KubernetesVersion { get => this._kubernetesVersion; set => this._kubernetesVersion = value; } + + /// Backing field for property. + private string _type; + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public ManagedClusterUpgradeSpec() + { + + } + } + /// The upgrade to apply to a ManagedCluster. + public partial interface IManagedClusterUpgradeSpec : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string KubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string Type { get; set; } + + } + /// The upgrade to apply to a ManagedCluster. + internal partial interface IManagedClusterUpgradeSpecInternal + + { + /// The Kubernetes version to upgrade the member clusters to. + string KubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.json.cs new file mode 100644 index 00000000000..c5a23de9723 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedClusterUpgradeSpec.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The upgrade to apply to a ManagedCluster. + public partial class ManagedClusterUpgradeSpec + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ManagedClusterUpgradeSpec(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedClusterUpgradeSpec(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_kubernetesVersion = If( json?.PropertyT("kubernetesVersion"), out var __jsonKubernetesVersion) ? (string)__jsonKubernetesVersion : (string)_kubernetesVersion;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != (((object)this._kubernetesVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._kubernetesVersion.ToString()) : null, "kubernetesVersion" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs new file mode 100644 index 00000000000..9ac5eb20926 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IManagedServiceIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentitiesTypeConverter.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs new file mode 100644 index 00000000000..3d5705c6096 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IManagedServiceIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.cs new file mode 100644 index 00000000000..3ec7ee0c0e1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities _userAssignedIdentity; + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get => (this._userAssignedIdentity = this._userAssignedIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentities()); 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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities 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.ContainerServiceFleet.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities UserAssignedIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentity.json.cs new file mode 100644 index 00000000000..5032dee04de --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ManagedServiceIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedServiceIdentity(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentities.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != this._userAssignedIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs new file mode 100644 index 00000000000..defad9560a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.PowerShell.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedServiceIdentityUserAssignedIdentities(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// + /// an instance of the model class. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedServiceIdentityUserAssignedIdentities(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 ManagedServiceIdentityUserAssignedIdentities(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.ContainerServiceFleet.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 identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityUserAssignedIdentitiesTypeConverter))] + public partial interface IManagedServiceIdentityUserAssignedIdentities + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.TypeConverter.cs new file mode 100644 index 00000000000..9468ff7486e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedServiceIdentityUserAssignedIdentitiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedServiceIdentityUserAssignedIdentities.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedServiceIdentityUserAssignedIdentities.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs new file mode 100644 index 00000000000..9efc0802997 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentitiesInternal + { + + /// + /// Creates an new instance. + /// + public ManagedServiceIdentityUserAssignedIdentities() + { + + } + } + /// The identities assigned to this resource by the user. + public partial interface IManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + + } + /// The identities assigned to this resource by the user. + internal partial interface IManagedServiceIdentityUserAssignedIdentitiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.dictionary.cs new file mode 100644 index 00000000000..f509d444203 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class ManagedServiceIdentityUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUserAssignedIdentity value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedServiceIdentityUserAssignedIdentities source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.json.cs new file mode 100644 index 00000000000..4d3bd0efba1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ManagedServiceIdentityUserAssignedIdentities.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class ManagedServiceIdentityUserAssignedIdentities + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedServiceIdentityUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ManagedServiceIdentityUserAssignedIdentities(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ManagedServiceIdentityUserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UserAssignedIdentity.FromJson(j) ,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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.PowerShell.cs new file mode 100644 index 00000000000..153994c39da --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.PowerShell.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status of a member update operation. + [System.ComponentModel.TypeConverter(typeof(MemberUpdateStatusTypeConverter))] + public partial class MemberUpdateStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IMemberUpdateStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MemberUpdateStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MemberUpdateStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MemberUpdateStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("ClusterResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).ClusterResourceId = (string) content.GetValueForProperty("ClusterResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).ClusterResourceId, global::System.Convert.ToString); + } + if (content.Contains("OperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).OperationId = (string) content.GetValueForProperty("OperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).OperationId, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusErrorMessage = (string) content.GetValueForProperty("StatusErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal MemberUpdateStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("ClusterResourceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).ClusterResourceId = (string) content.GetValueForProperty("ClusterResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).ClusterResourceId, global::System.Convert.ToString); + } + if (content.Contains("OperationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).OperationId = (string) content.GetValueForProperty("OperationId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).OperationId, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusErrorMessage = (string) content.GetValueForProperty("StatusErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).StatusErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.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.ContainerServiceFleet.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 status of a member update operation. + [System.ComponentModel.TypeConverter(typeof(MemberUpdateStatusTypeConverter))] + public partial interface IMemberUpdateStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.TypeConverter.cs new file mode 100644 index 00000000000..40996a5a132 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MemberUpdateStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IMemberUpdateStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MemberUpdateStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MemberUpdateStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MemberUpdateStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.cs new file mode 100644 index 00000000000..be0ec800e86 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.cs @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a member update operation. + public partial class MemberUpdateStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; } + + /// Backing field for property. + private string _clusterResourceId; + + /// The Azure resource id of the target Kubernetes cluster. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ClusterResourceId { get => this._clusterResourceId; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; } + + /// Backing field for property. + private string _message; + + /// The status message after processing the member update operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for ClusterResourceId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.ClusterResourceId { get => this._clusterResourceId; set { {_clusterResourceId = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for OperationId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.OperationId { get => this._operationId; set { {_operationId = value;} } } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error = value ?? null /* model class */; } + + /// Internal Acessors for StatusErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.StatusErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatusInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target = value ?? null; } + + /// Backing field for property. + private string _name; + + /// The name of the FleetMember. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _operationId; + + /// The operation resource id of the latest attempt to perform the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string OperationId { get => this._operationId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus _status; + + /// The status of the MemberUpdate operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; } + + /// Creates an new instance. + public MemberUpdateStatus() + { + + } + } + /// The status of a member update operation. + public partial interface IMemberUpdateStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The Azure resource id of the target Kubernetes cluster. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Azure resource id of the target Kubernetes cluster.", + SerializedName = @"clusterResourceId", + PossibleTypes = new [] { typeof(string) })] + string ClusterResourceId { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The status message after processing the member update operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The status message after processing the member update operation.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The name of the FleetMember. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the FleetMember.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The operation resource id of the latest attempt to perform the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The operation resource id of the latest attempt to perform the operation.", + SerializedName = @"operationId", + PossibleTypes = new [] { typeof(string) })] + string OperationId { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string StatusErrorMessage { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 status of a member update operation. + internal partial interface IMemberUpdateStatusInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The Azure resource id of the target Kubernetes cluster. + string ClusterResourceId { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The status message after processing the member update operation. + string Message { get; set; } + /// The name of the FleetMember. + string Name { get; set; } + /// The operation resource id of the latest attempt to perform the operation. + string OperationId { get; set; } + /// The status of the MemberUpdate operation. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// The error message. + string StatusErrorMessage { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.json.cs new file mode 100644 index 00000000000..46316f5a446 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/MemberUpdateStatus.json.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a member update operation. + public partial class MemberUpdateStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new MemberUpdateStatus(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal MemberUpdateStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus.FromJson(__jsonStatus) : _status;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_clusterResourceId = If( json?.PropertyT("clusterResourceId"), out var __jsonClusterResourceId) ? (string)__jsonClusterResourceId : (string)_clusterResourceId;} + {_operationId = If( json?.PropertyT("operationId"), out var __jsonOperationId) ? (string)__jsonOperationId : (string)_operationId;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)_message;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clusterResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._clusterResourceId.ToString()) : null, "clusterResourceId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._operationId.ToString()) : null, "operationId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.PowerShell.cs new file mode 100644 index 00000000000..354fdd24940 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The node image upgrade to be applied to the target nodes in update run. + [System.ComponentModel.TypeConverter(typeof(NodeImageSelectionTypeConverter))] + public partial class NodeImageSelection + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.INodeImageSelection DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new NodeImageSelection(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new NodeImageSelection(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal NodeImageSelection(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.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("CustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).CustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("CustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).CustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal NodeImageSelection(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.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("CustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).CustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("CustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal)this).CustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.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.ContainerServiceFleet.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 node image upgrade to be applied to the target nodes in update run. + [System.ComponentModel.TypeConverter(typeof(NodeImageSelectionTypeConverter))] + public partial interface INodeImageSelection + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.TypeConverter.cs new file mode 100644 index 00000000000..53115624add --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class NodeImageSelectionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.INodeImageSelection ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return NodeImageSelection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return NodeImageSelection.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return NodeImageSelection.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.cs new file mode 100644 index 00000000000..d476b46c710 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node image upgrade to be applied to the target nodes in update run. + public partial class NodeImageSelection : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _customNodeImageVersion; + + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List CustomNodeImageVersion { get => this._customNodeImageVersion; set => this._customNodeImageVersion = value; } + + /// Backing field for property. + private string _type; + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public NodeImageSelection() + { + + } + } + /// The node image upgrade to be applied to the target nodes in update run. + public partial interface INodeImageSelection : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.", + SerializedName = @"customNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List CustomNodeImageVersion { get; set; } + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string Type { get; set; } + + } + /// The node image upgrade to be applied to the target nodes in update run. + internal partial interface INodeImageSelectionInternal + + { + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + System.Collections.Generic.List CustomNodeImageVersion { get; set; } + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.json.cs new file mode 100644 index 00000000000..f0ab21db69f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelection.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node image upgrade to be applied to the target nodes in update run. + public partial class NodeImageSelection + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new NodeImageSelection(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal NodeImageSelection(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_customNodeImageVersion = If( json?.PropertyT("customNodeImageVersions"), out var __jsonCustomNodeImageVersions) ? If( __jsonCustomNodeImageVersions as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.INodeImageVersion) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersion.FromJson(__u) )) ))() : null : _customNodeImageVersion;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (null != this._customNodeImageVersion) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._customNodeImageVersion ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("customNodeImageVersions",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.PowerShell.cs new file mode 100644 index 00000000000..dd8c42b4af1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The node image upgrade specs for the update run. + [System.ComponentModel.TypeConverter(typeof(NodeImageSelectionStatusTypeConverter))] + public partial class NodeImageSelectionStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.INodeImageSelectionStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new NodeImageSelectionStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new NodeImageSelectionStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal NodeImageSelectionStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)this).SelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("SelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)this).SelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal NodeImageSelectionStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)this).SelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("SelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)this).SelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.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.ContainerServiceFleet.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 node image upgrade specs for the update run. + [System.ComponentModel.TypeConverter(typeof(NodeImageSelectionStatusTypeConverter))] + public partial interface INodeImageSelectionStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.TypeConverter.cs new file mode 100644 index 00000000000..fcbfeec3571 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class NodeImageSelectionStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.INodeImageSelectionStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return NodeImageSelectionStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return NodeImageSelectionStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return NodeImageSelectionStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.cs new file mode 100644 index 00000000000..e6531ea9e3c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node image upgrade specs for the update run. + public partial class NodeImageSelectionStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal + { + + /// Internal Acessors for SelectedNodeImageVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal.SelectedNodeImageVersion { get => this._selectedNodeImageVersion; set { {_selectedNodeImageVersion = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _selectedNodeImageVersion; + + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List SelectedNodeImageVersion { get => this._selectedNodeImageVersion; } + + /// Creates an new instance. + public NodeImageSelectionStatus() + { + + } + } + /// The node image upgrade specs for the update run. + public partial interface INodeImageSelectionStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The image versions to upgrade the nodes to.", + SerializedName = @"selectedNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List SelectedNodeImageVersion { get; } + + } + /// The node image upgrade specs for the update run. + internal partial interface INodeImageSelectionStatusInternal + + { + /// The image versions to upgrade the nodes to. + System.Collections.Generic.List SelectedNodeImageVersion { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.json.cs new file mode 100644 index 00000000000..cd18fc64fa7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageSelectionStatus.json.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node image upgrade specs for the update run. + public partial class NodeImageSelectionStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new NodeImageSelectionStatus(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal NodeImageSelectionStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_selectedNodeImageVersion = If( json?.PropertyT("selectedNodeImageVersions"), out var __jsonSelectedNodeImageVersions) ? If( __jsonSelectedNodeImageVersions as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.INodeImageVersion) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersion.FromJson(__u) )) ))() : null : _selectedNodeImageVersion;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._selectedNodeImageVersion) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._selectedNodeImageVersion ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("selectedNodeImageVersions",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.PowerShell.cs new file mode 100644 index 00000000000..16283ed0b03 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The node upgrade image version. + [System.ComponentModel.TypeConverter(typeof(NodeImageVersionTypeConverter))] + public partial class NodeImageVersion + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.INodeImageVersion DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new NodeImageVersion(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new NodeImageVersion(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal NodeImageVersion(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Version")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersionInternal)this).Version = (string) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersionInternal)this).Version, 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 NodeImageVersion(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Version")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersionInternal)this).Version = (string) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersionInternal)this).Version, 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.ContainerServiceFleet.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 node upgrade image version. + [System.ComponentModel.TypeConverter(typeof(NodeImageVersionTypeConverter))] + public partial interface INodeImageVersion + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.TypeConverter.cs new file mode 100644 index 00000000000..0a74c675b8c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class NodeImageVersionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.INodeImageVersion ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return NodeImageVersion.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return NodeImageVersion.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return NodeImageVersion.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.cs new file mode 100644 index 00000000000..71de4ed4a33 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node upgrade image version. + public partial class NodeImageVersion : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersionInternal + { + + /// Internal Acessors for Version + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersionInternal.Version { get => this._version; set { {_version = value;} } } + + /// Backing field for property. + private string _version; + + /// + /// The image version to upgrade the nodes to (e.g., 'AKSUbuntu-1804gen2containerd-2022.12.13'). + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Version { get => this._version; } + + /// Creates an new instance. + public NodeImageVersion() + { + + } + } + /// The node upgrade image version. + public partial interface INodeImageVersion : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The image version to upgrade the nodes to (e.g., 'AKSUbuntu-1804gen2containerd-2022.12.13'). + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The image version to upgrade the nodes to (e.g., 'AKSUbuntu-1804gen2containerd-2022.12.13').", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + string Version { get; } + + } + /// The node upgrade image version. + internal partial interface INodeImageVersionInternal + + { + /// + /// The image version to upgrade the nodes to (e.g., 'AKSUbuntu-1804gen2containerd-2022.12.13'). + /// + string Version { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.json.cs new file mode 100644 index 00000000000..169baf49985 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/NodeImageVersion.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The node upgrade image version. + public partial class NodeImageVersion + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new NodeImageVersion(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal NodeImageVersion(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_version = If( json?.PropertyT("version"), out var __jsonVersion) ? (string)__jsonVersion : (string)_version;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._version)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._version.ToString()) : null, "version" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..d78d817cc2f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..e289d6bdf72 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..8eb0d596154 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationDisplay()); set => this._display = value; } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for ActionType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.ActionType { get => this._actionType; set { {_actionType = value;} } } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Description = value ?? null; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Operation = value ?? null; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Provider = value ?? null; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)Display).Resource = value ?? null; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.ContainerServiceFleet.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..dcd69800c8f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..bd0a8adce65 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..6ef25066b74 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..8d68daacded --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..5557d48fcaa --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..22f0b65482f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..666c87109cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..0f82b3327f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..8503ca0db0c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ProxyResource.PowerShell.cs new file mode 100644 index 00000000000..a5be2e39903 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ProxyResource.TypeConverter.cs new file mode 100644 index 00000000000..f85d344c205 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/ProxyResource.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ProxyResource.cs new file mode 100644 index 00000000000..05c22653879 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ProxyResource.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ProxyResource.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/ProxyResource.json.cs new file mode 100644 index 00000000000..d90601ba9c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..97f84158ede --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..1537be565dd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..8cf0eb6de39 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Resource.cs @@ -0,0 +1,255 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)SystemData).LastModifiedByType; } + + /// 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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..e46cccc3575 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/SkipProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.PowerShell.cs new file mode 100644 index 00000000000..c5d519cabe1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The properties of a skip operation containing multiple skip requests. + [System.ComponentModel.TypeConverter(typeof(SkipPropertiesTypeConverter))] + public partial class SkipProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.ISkipProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SkipProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SkipProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SkipProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipPropertiesInternal)this).Target = (System.Collections.Generic.List) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipPropertiesInternal)this).Target, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SkipTargetTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SkipProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipPropertiesInternal)this).Target = (System.Collections.Generic.List) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipPropertiesInternal)this).Target, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SkipTargetTypeConverter.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.ContainerServiceFleet.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 properties of a skip operation containing multiple skip requests. + [System.ComponentModel.TypeConverter(typeof(SkipPropertiesTypeConverter))] + public partial interface ISkipProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.TypeConverter.cs new file mode 100644 index 00000000000..5f3e75bbb51 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SkipPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.ISkipProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SkipProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SkipProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SkipProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/SkipProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.cs new file mode 100644 index 00000000000..7f55208bc84 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of a skip operation containing multiple skip requests. + public partial class SkipProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipPropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _target; + + /// The targets to skip. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Target { get => this._target; set => this._target = value; } + + /// Creates an new instance. + public SkipProperties() + { + + } + } + /// The properties of a skip operation containing multiple skip requests. + public partial interface ISkipProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The targets to skip. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The targets to skip.", + SerializedName = @"targets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget) })] + System.Collections.Generic.List Target { get; set; } + + } + /// The properties of a skip operation containing multiple skip requests. + internal partial interface ISkipPropertiesInternal + + { + /// The targets to skip. + System.Collections.Generic.List Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.json.cs new file mode 100644 index 00000000000..44ef24ec99b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of a skip operation containing multiple skip requests. + public partial class SkipProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new SkipProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal SkipProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_target = If( json?.PropertyT("targets"), out var __jsonTargets) ? If( __jsonTargets as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ISkipTarget) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SkipTarget.FromJson(__u) )) ))() : null : _target;} + 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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._target) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._target ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("targets",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.PowerShell.cs new file mode 100644 index 00000000000..423737ee73a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The definition of a single skip request. + [System.ComponentModel.TypeConverter(typeof(SkipTargetTypeConverter))] + public partial class SkipTarget + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.ISkipTarget DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SkipTarget(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SkipTarget(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SkipTarget(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.ContainerServiceFleet.Models.ISkipTargetInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal)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 SkipTarget(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.ContainerServiceFleet.Models.ISkipTargetInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal)this).Name, 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.ContainerServiceFleet.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 definition of a single skip request. + [System.ComponentModel.TypeConverter(typeof(SkipTargetTypeConverter))] + public partial interface ISkipTarget + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.TypeConverter.cs new file mode 100644 index 00000000000..7f7b3e0e846 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SkipTargetTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.ISkipTarget ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SkipTarget.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SkipTarget.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SkipTarget.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/SkipTarget.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.cs new file mode 100644 index 00000000000..adb8975dc76 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The definition of a single skip request. + public partial class SkipTarget : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTargetInternal + { + + /// Backing field for property. + private string _name; + + /// + /// The skip target's name. + /// To skip a member/group/stage, use the member/group/stage's name; + /// Tp skip an after stage wait, use the parent stage's name. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _type; + + /// The skip target type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public SkipTarget() + { + + } + } + /// The definition of a single skip request. + public partial interface ISkipTarget : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// + /// The skip target's name. + /// To skip a member/group/stage, use the member/group/stage's name; + /// Tp skip an after stage wait, use the parent stage's name. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The skip target's name. + To skip a member/group/stage, use the member/group/stage's name; + Tp skip an after stage wait, use the parent stage's name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// The skip target type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The skip target type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Member", "Group", "Stage", "AfterStageWait")] + string Type { get; set; } + + } + /// The definition of a single skip request. + internal partial interface ISkipTargetInternal + + { + /// + /// The skip target's name. + /// To skip a member/group/stage, use the member/group/stage's name; + /// Tp skip an after stage wait, use the parent stage's name. + /// + string Name { get; set; } + /// The skip target type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Member", "Group", "Stage", "AfterStageWait")] + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.json.cs new file mode 100644 index 00000000000..b147a0072d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SkipTarget.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The definition of a single skip request. + public partial class SkipTarget + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new SkipTarget(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal SkipTarget(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..0bfbe325322 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..990aa384eba --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..cb618b5d33e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..20dd78657f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..ec04d3d5449 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResourceTagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..cd351a3b4fd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..c00acd498c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Type = value ?? null; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResourceTags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + 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.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags 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.ContainerServiceFleet.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..c1e413f428a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.TrackedResourceTags.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/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.PowerShell.cs new file mode 100644 index 00000000000..44655192a2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial class TrackedResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// 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.ContainerServiceFleet.Models.ITrackedResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 TrackedResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial interface ITrackedResourceTags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.TypeConverter.cs new file mode 100644 index 00000000000..38c80961a0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.ITrackedResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.cs new file mode 100644 index 00000000000..14b38ab5ac4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTagsInternal + { + + /// Creates an new instance. + public TrackedResourceTags() + { + + } + } + /// Resource tags. + public partial interface ITrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITrackedResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.dictionary.cs new file mode 100644 index 00000000000..01b41e7bb27 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.TrackedResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.json.cs new file mode 100644 index 00000000000..7710cefe4ec --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/TrackedResourceTags.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new TrackedResourceTags(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TrackedResourceTags(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.PowerShell.cs new file mode 100644 index 00000000000..a0cd527c2ad --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// A group to be updated. + [System.ComponentModel.TypeConverter(typeof(UpdateGroupTypeConverter))] + public partial class UpdateGroup + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateGroup DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateGroup(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateGroup(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateGroup(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.ContainerServiceFleet.Models.IUpdateGroupInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateGroup(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.ContainerServiceFleet.Models.IUpdateGroupInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// A group to be updated. + [System.ComponentModel.TypeConverter(typeof(UpdateGroupTypeConverter))] + public partial interface IUpdateGroup + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.TypeConverter.cs new file mode 100644 index 00000000000..27c3b2537bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateGroupTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateGroup ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateGroup.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateGroup.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateGroup.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.cs new file mode 100644 index 00000000000..edab7aeb9af --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A group to be updated. + public partial class UpdateGroup : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _afterGate; + + /// A list of Gates that will be created after this Group is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List AfterGate { get => this._afterGate; set => this._afterGate = value; } + + /// Backing field for property. + private System.Collections.Generic.List _beforeGate; + + /// A list of Gates that will be created before this Group is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List BeforeGate { get => this._beforeGate; set => this._beforeGate = value; } + + /// Backing field for property. + private string _name; + + /// + /// Name of the group. + /// It must match a group name of an existing fleet member. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public UpdateGroup() + { + + } + } + /// A group to be updated. + public partial interface IUpdateGroup : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// A list of Gates that will be created after this Group is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A list of Gates that will be created after this Group is executed.", + SerializedName = @"afterGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration) })] + System.Collections.Generic.List AfterGate { get; set; } + /// A list of Gates that will be created before this Group is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A list of Gates that will be created before this Group is executed.", + SerializedName = @"beforeGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration) })] + System.Collections.Generic.List BeforeGate { get; set; } + /// + /// Name of the group. + /// It must match a group name of an existing fleet member. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the group. + It must match a group name of an existing fleet member. ", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// A group to be updated. + internal partial interface IUpdateGroupInternal + + { + /// A list of Gates that will be created after this Group is executed. + System.Collections.Generic.List AfterGate { get; set; } + /// A list of Gates that will be created before this Group is executed. + System.Collections.Generic.List BeforeGate { get; set; } + /// + /// Name of the group. + /// It must match a group name of an existing fleet member. + /// + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.json.cs new file mode 100644 index 00000000000..873c99efc3d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroup.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A group to be updated. + public partial class UpdateGroup + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateGroup(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + if (null != this._beforeGate) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._beforeGate ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("beforeGates",__w); + } + if (null != this._afterGate) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __s in this._afterGate ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("afterGates",__r); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateGroup(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_beforeGate = If( json?.PropertyT("beforeGates"), out var __jsonBeforeGates) ? If( __jsonBeforeGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGateConfiguration) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfiguration.FromJson(__u) )) ))() : null : _beforeGate;} + {_afterGate = If( json?.PropertyT("afterGates"), out var __jsonAfterGates) ? If( __jsonAfterGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGateConfiguration) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfiguration.FromJson(__p) )) ))() : null : _afterGate;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.PowerShell.cs new file mode 100644 index 00000000000..378df3903b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.PowerShell.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status of a UpdateGroup. + [System.ComponentModel.TypeConverter(typeof(UpdateGroupStatusTypeConverter))] + public partial class UpdateGroupStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateGroupStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateGroupStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateGroupStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateGroupStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Member")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Member = (System.Collections.Generic.List) content.GetValueForProperty("Member",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Member, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.MemberUpdateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateGroupStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Member")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Member = (System.Collections.Generic.List) content.GetValueForProperty("Member",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Member, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.MemberUpdateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The status of a UpdateGroup. + [System.ComponentModel.TypeConverter(typeof(UpdateGroupStatusTypeConverter))] + public partial interface IUpdateGroupStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.TypeConverter.cs new file mode 100644 index 00000000000..50d84989d91 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateGroupStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateGroupStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateGroupStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateGroupStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateGroupStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.cs new file mode 100644 index 00000000000..676f78d32a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.cs @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a UpdateGroup. + public partial class UpdateGroupStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; } + + /// Backing field for property. + private System.Collections.Generic.List _afterGate; + + /// The list of Gates that will run after this UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List AfterGate { get => this._afterGate; } + + /// Backing field for property. + private System.Collections.Generic.List _beforeGate; + + /// The list of Gates that will run before this UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List BeforeGate { get => this._beforeGate; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; } + + /// Backing field for property. + private System.Collections.Generic.List _member; + + /// The list of member this UpdateGroup updates. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Member { get => this._member; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for AfterGate + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.AfterGate { get => this._afterGate; set { {_afterGate = value;} } } + + /// Internal Acessors for BeforeGate + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.BeforeGate { get => this._beforeGate; set { {_beforeGate = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Member + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Member { get => this._member; set { {_member = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error = value ?? null /* model class */; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatusInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target = value ?? null; } + + /// Backing field for property. + private string _name; + + /// The name of the UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus _status; + + /// The status of the UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; } + + /// Creates an new instance. + public UpdateGroupStatus() + { + + } + } + /// The status of a UpdateGroup. + public partial interface IUpdateGroupStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The list of Gates that will run after this UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The list of Gates that will run after this UpdateGroup.", + SerializedName = @"afterGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus) })] + System.Collections.Generic.List AfterGate { get; } + /// The list of Gates that will run before this UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The list of Gates that will run before this UpdateGroup.", + SerializedName = @"beforeGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus) })] + System.Collections.Generic.List BeforeGate { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The list of member this UpdateGroup updates. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The list of member this UpdateGroup updates.", + SerializedName = @"members", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IMemberUpdateStatus) })] + System.Collections.Generic.List Member { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 name of the UpdateGroup. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the UpdateGroup.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 status of a UpdateGroup. + internal partial interface IUpdateGroupStatusInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The list of Gates that will run after this UpdateGroup. + System.Collections.Generic.List AfterGate { get; set; } + /// The list of Gates that will run before this UpdateGroup. + System.Collections.Generic.List BeforeGate { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The list of member this UpdateGroup updates. + System.Collections.Generic.List Member { get; set; } + /// The error message. + string Message { get; set; } + /// The name of the UpdateGroup. + string Name { get; set; } + /// The status of the UpdateGroup. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.json.cs new file mode 100644 index 00000000000..60b6b403210 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateGroupStatus.json.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a UpdateGroup. + public partial class UpdateGroupStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateGroupStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._member) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._member ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("members",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._beforeGate) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __s in this._beforeGate ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("beforeGates",__r); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._afterGate) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __n in this._afterGate ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("afterGates",__m); + } + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateGroupStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus.FromJson(__jsonStatus) : _status;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_member = If( json?.PropertyT("members"), out var __jsonMembers) ? If( __jsonMembers as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IMemberUpdateStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.MemberUpdateStatus.FromJson(__u) )) ))() : null : _member;} + {_beforeGate = If( json?.PropertyT("beforeGates"), out var __jsonBeforeGates) ? If( __jsonBeforeGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRunGateStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatus.FromJson(__p) )) ))() : null : _beforeGate;} + {_afterGate = If( json?.PropertyT("afterGates"), out var __jsonAfterGates) ? If( __jsonAfterGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatus.FromJson(__k) )) ))() : null : _afterGate;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.PowerShell.cs new file mode 100644 index 00000000000..c2bff410c04 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.PowerShell.cs @@ -0,0 +1,458 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// A multi-stage process to perform update operations across members of a Fleet. + [System.ComponentModel.TypeConverter(typeof(UpdateRunTypeConverter))] + public partial class UpdateRun + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRun DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRun(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRun(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRun(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.ContainerServiceFleet.Models.IUpdateRunInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdate = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate) content.GetValueForProperty("ManagedClusterUpdate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdate, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AutoUpgradeProfileId = (string) content.GetValueForProperty("AutoUpgradeProfileId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AutoUpgradeProfileId, global::System.Convert.ToString); + } + if (content.Contains("UpdateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("UpdateStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + if (content.Contains("ManagedClusterUpdateUpgrade")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateUpgrade = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec) content.GetValueForProperty("ManagedClusterUpdateUpgrade",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateUpgrade, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpecTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdateNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection) content.GetValueForProperty("ManagedClusterUpdateNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("UpgradeKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeKubernetesVersion = (string) content.GetValueForProperty("UpgradeKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("StatusNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus) content.GetValueForProperty("StatusNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStage = (System.Collections.Generic.List) content.GetValueForProperty("StatusStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("UpgradeType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeType = (string) content.GetValueForProperty("UpgradeType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeType, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionCustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionCustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionCustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionCustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("NodeImageSelectionSelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionSelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionSelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionSelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateRun(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.ContainerServiceFleet.Models.IUpdateRunInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ETag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ETag, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdate = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate) content.GetValueForProperty("ManagedClusterUpdate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdate, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AutoUpgradeProfileId = (string) content.GetValueForProperty("AutoUpgradeProfileId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AutoUpgradeProfileId, global::System.Convert.ToString); + } + if (content.Contains("UpdateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("UpdateStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpdateStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + if (content.Contains("ManagedClusterUpdateUpgrade")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateUpgrade = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec) content.GetValueForProperty("ManagedClusterUpdateUpgrade",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateUpgrade, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpecTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdateNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection) content.GetValueForProperty("ManagedClusterUpdateNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).ManagedClusterUpdateNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("UpgradeKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeKubernetesVersion = (string) content.GetValueForProperty("UpgradeKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("StatusNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus) content.GetValueForProperty("StatusNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStage = (System.Collections.Generic.List) content.GetValueForProperty("StatusStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("UpgradeType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeType = (string) content.GetValueForProperty("UpgradeType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).UpgradeType, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionCustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionCustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionCustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionCustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("NodeImageSelectionSelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionSelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionSelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).NodeImageSelectionSelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// A multi-stage process to perform update operations across members of a Fleet. + [System.ComponentModel.TypeConverter(typeof(UpdateRunTypeConverter))] + public partial interface IUpdateRun + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.TypeConverter.cs new file mode 100644 index 00000000000..6146b0bffe2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRun ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRun.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRun.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRun.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRun.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.cs new file mode 100644 index 00000000000..b01c2706650 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.cs @@ -0,0 +1,645 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A multi-stage process to perform update operations across members of a Fleet. + public partial class UpdateRun : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(); + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).AdditionalInfo; } + + /// AutoUpgradeProfileId is the id of an auto upgrade profile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AutoUpgradeProfileId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).AutoUpgradeProfileId; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Detail; } + + /// Backing field for property. + private string _eTag; + + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Message; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Id = value ?? null; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name = value ?? null; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// Internal Acessors for SystemDataLastModifiedBy + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// Internal Acessors for SystemDataLastModifiedByType + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type = value ?? null; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for AutoUpgradeProfileId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.AutoUpgradeProfileId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).AutoUpgradeProfileId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).AutoUpgradeProfileId = value ?? null; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for ManagedClusterUpdate + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.ManagedClusterUpdate { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ManagedClusterUpdate; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ManagedClusterUpdate = value ?? null /* model class */; } + + /// Internal Acessors for ManagedClusterUpdateNodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.ManagedClusterUpdateNodeImageSelection { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ManagedClusterUpdateNodeImageSelection; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ManagedClusterUpdateNodeImageSelection = value ?? null /* model class */; } + + /// Internal Acessors for ManagedClusterUpdateUpgrade + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.ManagedClusterUpdateUpgrade { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ManagedClusterUpdateUpgrade; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ManagedClusterUpdateUpgrade = value ?? null /* model class */; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Message = value ?? null; } + + /// Internal Acessors for NodeImageSelectionSelectedNodeImageVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.NodeImageSelectionSelectedNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionSelectedNodeImageVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionSelectedNodeImageVersion = value ?? null /* arrayOf */; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ProvisioningState = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Status = value ?? null /* model class */; } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusCompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusCompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusError = value ?? null /* model class */; } + + /// Internal Acessors for StatusNodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.StatusNodeImageSelection { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusNodeImageSelection; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusNodeImageSelection = value ?? null /* model class */; } + + /// Internal Acessors for StatusStage + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.StatusStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusStage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusStage = value ?? null /* arrayOf */; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusState = value ?? null; } + + /// Internal Acessors for Strategy + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Strategy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Strategy; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Strategy = value ?? null /* model class */; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Target = value ?? null; } + + /// Internal Acessors for UpdateStatus + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunInternal.UpdateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpdateStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpdateStatus = value ?? null /* model class */; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Name; } + + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionCustomNodeImageVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionCustomNodeImageVersion = value ?? null /* arrayOf */; } + + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionSelectedNodeImageVersion; } + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string NodeImageSelectionType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).NodeImageSelectionType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunProperties()); set => this._property = value; } + + /// The provisioning state of the UpdateRun resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusCompletedTime; } + + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StatusStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusStage; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusStartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StatusState; } + + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StrategyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StrategyStage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).StrategyStage = value ?? null /* arrayOf */; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemData = value ?? null /* model class */; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).Target; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IResourceInternal)__proxyResource).Type; } + + /// + /// The resource id of the FleetUpdateStrategy resource to reference. + /// When creating a new run, there are three ways to define a strategy for the run: + /// 1. Define a new strategy in place: Set the "strategy" field. + /// 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + /// 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. + /// (since 2023-08-15-preview) + /// Setting both "updateStrategyId" and "strategy" is invalid. + /// UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in + /// the "strategy" field. + /// Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + /// UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpdateStrategyId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpdateStrategyId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpdateStrategyId = value ?? null; } + + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpgradeKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpgradeKubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpgradeKubernetesVersion = value ?? null; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpgradeType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpgradeType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)Property).UpgradeType = value ?? null; } + + /// Creates an new instance. + public UpdateRun() + { + + } + + /// 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.ContainerServiceFleet.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// A multi-stage process to perform update operations across members of a Fleet. + public partial interface IUpdateRun : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResource + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// AutoUpgradeProfileId is the id of an auto upgrade profile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"AutoUpgradeProfileId is the id of an auto upgrade profile resource.", + SerializedName = @"autoUpgradeProfileId", + PossibleTypes = new [] { typeof(string) })] + string AutoUpgradeProfileId { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.", + SerializedName = @"customNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get; set; } + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The image versions to upgrade the nodes to.", + SerializedName = @"selectedNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get; } + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string NodeImageSelectionType { get; set; } + /// The provisioning state of the UpdateRun resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the UpdateRun resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The stages composing an update run. Stages are run sequentially withing an UpdateRun.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus) })] + System.Collections.Generic.List StatusStage { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + System.Collections.Generic.List StrategyStage { get; set; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 resource id of the FleetUpdateStrategy resource to reference. + /// When creating a new run, there are three ways to define a strategy for the run: + /// 1. Define a new strategy in place: Set the "strategy" field. + /// 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + /// 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. + /// (since 2023-08-15-preview) + /// Setting both "updateStrategyId" and "strategy" is invalid. + /// UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in + /// the "strategy" field. + /// Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + /// UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource id of the FleetUpdateStrategy resource to reference. + + When creating a new run, there are three ways to define a strategy for the run: + 1. Define a new strategy in place: Set the ""strategy"" field. + 2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview) + 3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview) + + Setting both ""updateStrategyId"" and ""strategy"" is invalid. + + UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. + Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + string UpdateStrategyId { get; set; } + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string UpgradeKubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string UpgradeType { get; set; } + + } + /// A multi-stage process to perform update operations across members of a Fleet. + internal partial interface IUpdateRunInternal : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IProxyResourceInternal + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// AutoUpgradeProfileId is the id of an auto upgrade profile resource. + string AutoUpgradeProfileId { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// + /// If eTag is provided in the response body, it may also be provided as a header per the normal etag convention. Entity tags + /// are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section + /// 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + /// + string ETag { get; set; } + /// + /// The update to be applied to all clusters in the UpdateRun. The managedClusterUpdate can be modified until the run is started. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate ManagedClusterUpdate { get; set; } + /// The node image upgrade to be applied to the target nodes in update run. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection ManagedClusterUpdateNodeImageSelection { get; set; } + /// The upgrade to apply to the ManagedClusters. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec ManagedClusterUpdateUpgrade { get; set; } + /// The error message. + string Message { get; set; } + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get; set; } + /// The image versions to upgrade the nodes to. + System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get; set; } + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string NodeImageSelectionType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties Property { get; set; } + /// The provisioning state of the UpdateRun resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// The status of the UpdateRun. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// + /// The node image upgrade specs for the update run. It is only set in update run when `NodeImageSelection.type` is `Consistent`. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus StatusNodeImageSelection { get; set; } + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + System.Collections.Generic.List StatusStage { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// + /// The strategy defines the order in which the clusters will be updated. + /// If not set, all members will be updated sequentially. The UpdateRun status will show a single UpdateStage and a single + /// UpdateGroup targeting all members. + /// The strategy of the UpdateRun can be modified until the run is started. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Strategy { get; set; } + /// The list of stages that compose this update run. Min size: 1. + System.Collections.Generic.List StrategyStage { get; set; } + /// The error target. + string Target { get; set; } + /// The status of the UpdateRun. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus UpdateStatus { get; set; } + /// + /// The resource id of the FleetUpdateStrategy resource to reference. + /// When creating a new run, there are three ways to define a strategy for the run: + /// 1. Define a new strategy in place: Set the "strategy" field. + /// 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + /// 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. + /// (since 2023-08-15-preview) + /// Setting both "updateStrategyId" and "strategy" is invalid. + /// UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in + /// the "strategy" field. + /// Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + /// UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + string UpdateStrategyId { get; set; } + /// The Kubernetes version to upgrade the member clusters to. + string UpgradeKubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string UpgradeType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.json.cs new file mode 100644 index 00000000000..6ef4a37e7f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRun.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// A multi-stage process to perform update operations across members of a Fleet. + public partial class UpdateRun + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRun(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRun(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunProperties.FromJson(__jsonProperties) : _property;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)_eTag;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.PowerShell.cs new file mode 100644 index 00000000000..a7d46be5a38 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status of the Gate, as represented in the Update Run. + [System.ComponentModel.TypeConverter(typeof(UpdateRunGateStatusTypeConverter))] + public partial class UpdateRunGateStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRunGateStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRunGateStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRunGateStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunGateStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("GateId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).GateId = (string) content.GetValueForProperty("GateId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).GateId, global::System.Convert.ToString); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateRunGateStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("DisplayName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).DisplayName = (string) content.GetValueForProperty("DisplayName",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).DisplayName, global::System.Convert.ToString); + } + if (content.Contains("GateId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).GateId = (string) content.GetValueForProperty("GateId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).GateId, global::System.Convert.ToString); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The status of the Gate, as represented in the Update Run. + [System.ComponentModel.TypeConverter(typeof(UpdateRunGateStatusTypeConverter))] + public partial interface IUpdateRunGateStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.TypeConverter.cs new file mode 100644 index 00000000000..d100601e4a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunGateStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRunGateStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRunGateStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRunGateStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRunGateStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.cs new file mode 100644 index 00000000000..34fadb358f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.cs @@ -0,0 +1,257 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of the Gate, as represented in the Update Run. + public partial class UpdateRunGateStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; } + + /// Backing field for property. + private string _displayName; + + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string DisplayName { get => this._displayName; } + + /// Backing field for property. + private string _gateId; + + /// The resource id of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string GateId { get => this._gateId; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for DisplayName + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.DisplayName { get => this._displayName; set { {_displayName = value;} } } + + /// Internal Acessors for GateId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.GateId { get => this._gateId; set { {_gateId = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error = value ?? null /* model class */; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatusInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus _status; + + /// The status of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; } + + /// Creates an new instance. + public UpdateRunGateStatus() + { + + } + } + /// The status of the Gate, as represented in the Update Run. + public partial interface IUpdateRunGateStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The human-readable display name of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The human-readable display name of the Gate.", + SerializedName = @"displayName", + PossibleTypes = new [] { typeof(string) })] + string DisplayName { get; } + /// The resource id of the Gate. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The resource id of the Gate.", + SerializedName = @"gateId", + PossibleTypes = new [] { typeof(string) })] + string GateId { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 status of the Gate, as represented in the Update Run. + internal partial interface IUpdateRunGateStatusInternal + + { + /// 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 human-readable display name of the Gate. + string DisplayName { get; set; } + /// The resource id of the Gate. + string GateId { get; set; } + /// The error message. + string Message { get; set; } + /// The status of the Gate. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.json.cs new file mode 100644 index 00000000000..c94fb804982 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateStatus.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of the Gate, as represented in the Update Run. + public partial class UpdateRunGateStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRunGateStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._displayName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._displayName.ToString()) : null, "displayName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._gateId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._gateId.ToString()) : null, "gateId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRunGateStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus.FromJson(__jsonStatus) : _status;} + {_displayName = If( json?.PropertyT("displayName"), out var __jsonDisplayName) ? (string)__jsonDisplayName : (string)_displayName;} + {_gateId = If( json?.PropertyT("gateId"), out var __jsonGateId) ? (string)__jsonGateId : (string)_gateId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.PowerShell.cs new file mode 100644 index 00000000000..1dc87b9c260 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.PowerShell.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The properties of the Update Run that the Gate is targeting. + [System.ComponentModel.TypeConverter(typeof(UpdateRunGateTargetPropertiesTypeConverter))] + public partial class UpdateRunGateTargetProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRunGateTargetProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRunGateTargetProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunGateTargetProperties(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.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Stage = (string) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Stage, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("Timing")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Timing = (string) content.GetValueForProperty("Timing",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Timing, 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 UpdateRunGateTargetProperties(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.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Stage = (string) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Stage, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Group = (string) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Group, global::System.Convert.ToString); + } + if (content.Contains("Timing")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Timing = (string) content.GetValueForProperty("Timing",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal)this).Timing, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The properties of the Update Run that the Gate is targeting. + [System.ComponentModel.TypeConverter(typeof(UpdateRunGateTargetPropertiesTypeConverter))] + public partial interface IUpdateRunGateTargetProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.TypeConverter.cs new file mode 100644 index 00000000000..1177f88e962 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunGateTargetPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRunGateTargetProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRunGateTargetProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRunGateTargetProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.cs new file mode 100644 index 00000000000..26a5a135c34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the Update Run that the Gate is targeting. + public partial class UpdateRunGateTargetProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal + { + + /// Backing field for property. + private string _group; + + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Group { get => this._group; } + + /// Internal Acessors for Group + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal.Group { get => this._group; set { {_group = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Stage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetPropertiesInternal.Stage { get => this._stage; set { {_stage = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _stage; + + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Stage { get => this._stage; } + + /// Backing field for property. + private string _timing; + + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Timing { get => this._timing; set => this._timing = value; } + + /// Creates an new instance. + public UpdateRunGateTargetProperties() + { + + } + } + /// The properties of the Update Run that the Gate is targeting. + public partial interface IUpdateRunGateTargetProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The Update Group of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Group of the Update Run.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + string Group { get; } + /// The name of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the Update Run.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The Update Stage of the Update Run. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The Update Stage of the Update Run.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + string Stage { get; } + /// Whether the Gate is placed before or after the update itself. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Whether the Gate is placed before or after the update itself.", + SerializedName = @"timing", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string Timing { get; set; } + + } + /// The properties of the Update Run that the Gate is targeting. + internal partial interface IUpdateRunGateTargetPropertiesInternal + + { + /// The Update Group of the Update Run. + string Group { get; set; } + /// The name of the Update Run. + string Name { get; set; } + /// The Update Stage of the Update Run. + string Stage { get; set; } + /// Whether the Gate is placed before or after the update itself. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Before", "After")] + string Timing { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.json.cs new file mode 100644 index 00000000000..1c479249998 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunGateTargetProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the Update Run that the Gate is targeting. + public partial class UpdateRunGateTargetProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateTargetProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRunGateTargetProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._stage)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._stage.ToString()) : null, "stage" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._group)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._group.ToString()) : null, "group" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._timing)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._timing.ToString()) : null, "timing" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRunGateTargetProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_stage = If( json?.PropertyT("stage"), out var __jsonStage) ? (string)__jsonStage : (string)_stage;} + {_group = If( json?.PropertyT("group"), out var __jsonGroup) ? (string)__jsonGroup : (string)_group;} + {_timing = If( json?.PropertyT("timing"), out var __jsonTiming) ? (string)__jsonTiming : (string)_timing;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.PowerShell.cs new file mode 100644 index 00000000000..0b8042637a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The response of a UpdateRun list operation. + [System.ComponentModel.TypeConverter(typeof(UpdateRunListResultTypeConverter))] + public partial class UpdateRunListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRunListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRunListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRunListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunListResult(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.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal)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 UpdateRunListResult(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.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The response of a UpdateRun list operation. + [System.ComponentModel.TypeConverter(typeof(UpdateRunListResultTypeConverter))] + public partial interface IUpdateRunListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.TypeConverter.cs new file mode 100644 index 00000000000..bb0831f65b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRunListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRunListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRunListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRunListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.cs new file mode 100644 index 00000000000..e65dd81c141 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a UpdateRun list operation. + public partial class UpdateRunListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The UpdateRun items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public UpdateRunListResult() + { + + } + } + /// The response of a UpdateRun list operation. + public partial interface IUpdateRunListResult : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 UpdateRun items on this page + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The UpdateRun items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a UpdateRun list operation. + internal partial interface IUpdateRunListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The UpdateRun items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.json.cs new file mode 100644 index 00000000000..270ee2689ac --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunListResult.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The response of a UpdateRun list operation. + public partial class UpdateRunListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRunListResult(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRunListResult(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.PowerShell.cs new file mode 100644 index 00000000000..df2eddec0ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.PowerShell.cs @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The properties of the UpdateRun. + [System.ComponentModel.TypeConverter(typeof(UpdateRunPropertiesTypeConverter))] + public partial class UpdateRunProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRunProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRunProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRunProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdate = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate) content.GetValueForProperty("ManagedClusterUpdate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdate, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AutoUpgradeProfileId = (string) content.GetValueForProperty("AutoUpgradeProfileId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AutoUpgradeProfileId, global::System.Convert.ToString); + } + if (content.Contains("UpdateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("UpdateStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + if (content.Contains("ManagedClusterUpdateUpgrade")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateUpgrade = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec) content.GetValueForProperty("ManagedClusterUpdateUpgrade",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateUpgrade, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpecTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdateNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection) content.GetValueForProperty("ManagedClusterUpdateNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("UpgradeKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeKubernetesVersion = (string) content.GetValueForProperty("UpgradeKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("StatusNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus) content.GetValueForProperty("StatusNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStage = (System.Collections.Generic.List) content.GetValueForProperty("StatusStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("UpgradeType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeType = (string) content.GetValueForProperty("UpgradeType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeType, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionCustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionCustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionCustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionCustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("NodeImageSelectionSelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionSelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionSelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionSelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateRunProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Strategy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Strategy = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy) content.GetValueForProperty("Strategy",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Strategy, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategyTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdate = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate) content.GetValueForProperty("ManagedClusterUpdate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdate, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdateTypeConverter.ConvertFrom); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatusTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("UpdateStrategyId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStrategyId = (string) content.GetValueForProperty("UpdateStrategyId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStrategyId, global::System.Convert.ToString); + } + if (content.Contains("AutoUpgradeProfileId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AutoUpgradeProfileId = (string) content.GetValueForProperty("AutoUpgradeProfileId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AutoUpgradeProfileId, global::System.Convert.ToString); + } + if (content.Contains("UpdateStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("UpdateStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpdateStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StrategyStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StrategyStage = (System.Collections.Generic.List) content.GetValueForProperty("StrategyStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StrategyStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + if (content.Contains("ManagedClusterUpdateUpgrade")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateUpgrade = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec) content.GetValueForProperty("ManagedClusterUpdateUpgrade",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateUpgrade, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpgradeSpecTypeConverter.ConvertFrom); + } + if (content.Contains("ManagedClusterUpdateNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection) content.GetValueForProperty("ManagedClusterUpdateNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).ManagedClusterUpdateNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionTypeConverter.ConvertFrom); + } + if (content.Contains("UpgradeKubernetesVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeKubernetesVersion = (string) content.GetValueForProperty("UpgradeKubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeKubernetesVersion, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionType = (string) content.GetValueForProperty("NodeImageSelectionType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionType, global::System.Convert.ToString); + } + if (content.Contains("StatusNodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusNodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus) content.GetValueForProperty("StatusNodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusNodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatusTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStage = (System.Collections.Generic.List) content.GetValueForProperty("StatusStage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("UpgradeType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeType = (string) content.GetValueForProperty("UpgradeType",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).UpgradeType, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionCustomNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionCustomNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionCustomNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionCustomNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("NodeImageSelectionSelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionSelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionSelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).NodeImageSelectionSelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The properties of the UpdateRun. + [System.ComponentModel.TypeConverter(typeof(UpdateRunPropertiesTypeConverter))] + public partial interface IUpdateRunProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.TypeConverter.cs new file mode 100644 index 00000000000..c05cfcdeaf6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRunProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRunProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRunProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRunProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.cs new file mode 100644 index 00000000000..e17bf4b606e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the UpdateRun. + public partial class UpdateRunProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).AdditionalInfo; } + + /// Backing field for property. + private string _autoUpgradeProfileId; + + /// AutoUpgradeProfileId is the id of an auto upgrade profile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string AutoUpgradeProfileId { get => this._autoUpgradeProfileId; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate _managedClusterUpdate; + + /// + /// The update to be applied to all clusters in the UpdateRun. The managedClusterUpdate can be modified until the run is started. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate ManagedClusterUpdate { get => (this._managedClusterUpdate = this._managedClusterUpdate ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdate()); set => this._managedClusterUpdate = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for AutoUpgradeProfileId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.AutoUpgradeProfileId { get => this._autoUpgradeProfileId; set { {_autoUpgradeProfileId = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for ManagedClusterUpdate + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.ManagedClusterUpdate { get => (this._managedClusterUpdate = this._managedClusterUpdate ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdate()); set { {_managedClusterUpdate = value;} } } + + /// Internal Acessors for ManagedClusterUpdateNodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.ManagedClusterUpdateNodeImageSelection { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).NodeImageSelection; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).NodeImageSelection = value ?? null /* model class */; } + + /// Internal Acessors for ManagedClusterUpdateUpgrade + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.ManagedClusterUpdateUpgrade { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).Upgrade; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).Upgrade = value ?? null /* model class */; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for NodeImageSelectionSelectedNodeImageVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.NodeImageSelectionSelectedNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).NodeImageSelectionSelectedNodeImageVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).NodeImageSelectionSelectedNodeImageVersion = value ?? null /* arrayOf */; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusCompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusCompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusError = value ?? null /* model class */; } + + /// Internal Acessors for StatusNodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.StatusNodeImageSelection { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).NodeImageSelection; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).NodeImageSelection = value ?? null /* model class */; } + + /// Internal Acessors for StatusStage + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.StatusStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Stage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Stage = value ?? null /* arrayOf */; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusState = value ?? null; } + + /// Internal Acessors for Strategy + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.Strategy { get => (this._strategy = this._strategy ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategy()); set { {_strategy = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Target = value ?? null; } + + /// Internal Acessors for UpdateStatus + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunPropertiesInternal.UpdateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Status = value ?? null /* model class */; } + + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).NodeImageSelectionCustomNodeImageVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).NodeImageSelectionCustomNodeImageVersion = value ?? null /* arrayOf */; } + + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).NodeImageSelectionSelectedNodeImageVersion; } + + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string NodeImageSelectionType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).NodeImageSelectionType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).NodeImageSelectionType = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state of the UpdateRun resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus _status; + + /// The status of the UpdateRun. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusCompletedTime; } + + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StatusStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Stage; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusStartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).StatusState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy _strategy; + + /// + /// The strategy defines the order in which the clusters will be updated. + /// If not set, all members will be updated sequentially. The UpdateRun status will show a single UpdateStage and a single + /// UpdateGroup targeting all members. + /// The strategy of the UpdateRun can be modified until the run is started. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Strategy { get => (this._strategy = this._strategy ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategy()); set => this._strategy = value; } + + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StrategyStage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)Strategy).Stage; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)Strategy).Stage = value ?? null /* arrayOf */; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)Status).Target; } + + /// Backing field for property. + private string _updateStrategyId; + + /// + /// The resource id of the FleetUpdateStrategy resource to reference. + /// When creating a new run, there are three ways to define a strategy for the run: + /// 1. Define a new strategy in place: Set the "strategy" field. + /// 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + /// 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. + /// (since 2023-08-15-preview) + /// Setting both "updateStrategyId" and "strategy" is invalid. + /// UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in + /// the "strategy" field. + /// Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + /// UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string UpdateStrategyId { get => this._updateStrategyId; set => this._updateStrategyId = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpgradeKubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).UpgradeKubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).UpgradeKubernetesVersion = value ?? null; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string UpgradeType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).UpgradeType; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdateInternal)ManagedClusterUpdate).UpgradeType = value ; } + + /// Creates an new instance. + public UpdateRunProperties() + { + + } + } + /// The properties of the UpdateRun. + public partial interface IUpdateRunProperties : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// AutoUpgradeProfileId is the id of an auto upgrade profile resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"AutoUpgradeProfileId is the id of an auto upgrade profile resource.", + SerializedName = @"autoUpgradeProfileId", + PossibleTypes = new [] { typeof(string) })] + string AutoUpgradeProfileId { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.", + SerializedName = @"customNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get; set; } + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The image versions to upgrade the nodes to.", + SerializedName = @"selectedNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get; } + /// The node image upgrade type. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string NodeImageSelectionType { get; set; } + /// The provisioning state of the UpdateRun resource. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The provisioning state of the UpdateRun resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The stages composing an update run. Stages are run sequentially withing an UpdateRun.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus) })] + System.Collections.Generic.List StatusStage { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + System.Collections.Generic.List StrategyStage { get; set; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 resource id of the FleetUpdateStrategy resource to reference. + /// When creating a new run, there are three ways to define a strategy for the run: + /// 1. Define a new strategy in place: Set the "strategy" field. + /// 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + /// 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. + /// (since 2023-08-15-preview) + /// Setting both "updateStrategyId" and "strategy" is invalid. + /// UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in + /// the "strategy" field. + /// Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + /// UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The resource id of the FleetUpdateStrategy resource to reference. + + When creating a new run, there are three ways to define a strategy for the run: + 1. Define a new strategy in place: Set the ""strategy"" field. + 2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview) + 3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview) + + Setting both ""updateStrategyId"" and ""strategy"" is invalid. + + UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. + Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + string UpdateStrategyId { get; set; } + /// The Kubernetes version to upgrade the member clusters to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string UpgradeKubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string UpgradeType { get; set; } + + } + /// The properties of the UpdateRun. + internal partial interface IUpdateRunPropertiesInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// AutoUpgradeProfileId is the id of an auto upgrade profile resource. + string AutoUpgradeProfileId { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// + /// The update to be applied to all clusters in the UpdateRun. The managedClusterUpdate can be modified until the run is started. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpdate ManagedClusterUpdate { get; set; } + /// The node image upgrade to be applied to the target nodes in update run. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelection ManagedClusterUpdateNodeImageSelection { get; set; } + /// The upgrade to apply to the ManagedClusters. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IManagedClusterUpgradeSpec ManagedClusterUpdateUpgrade { get; set; } + /// The error message. + string Message { get; set; } + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + System.Collections.Generic.List NodeImageSelectionCustomNodeImageVersion { get; set; } + /// The image versions to upgrade the nodes to. + System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get; set; } + /// The node image upgrade type. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + string NodeImageSelectionType { get; set; } + /// The provisioning state of the UpdateRun resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// The status of the UpdateRun. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// + /// The node image upgrade specs for the update run. It is only set in update run when `NodeImageSelection.type` is `Consistent`. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus StatusNodeImageSelection { get; set; } + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + System.Collections.Generic.List StatusStage { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// + /// The strategy defines the order in which the clusters will be updated. + /// If not set, all members will be updated sequentially. The UpdateRun status will show a single UpdateStage and a single + /// UpdateGroup targeting all members. + /// The strategy of the UpdateRun can be modified until the run is started. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy Strategy { get; set; } + /// The list of stages that compose this update run. Min size: 1. + System.Collections.Generic.List StrategyStage { get; set; } + /// The error target. + string Target { get; set; } + /// The status of the UpdateRun. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus UpdateStatus { get; set; } + /// + /// The resource id of the FleetUpdateStrategy resource to reference. + /// When creating a new run, there are three ways to define a strategy for the run: + /// 1. Define a new strategy in place: Set the "strategy" field. + /// 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + /// 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. + /// (since 2023-08-15-preview) + /// Setting both "updateStrategyId" and "strategy" is invalid. + /// UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in + /// the "strategy" field. + /// Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + /// UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + string UpdateStrategyId { get; set; } + /// The Kubernetes version to upgrade the member clusters to. + string UpgradeKubernetesVersion { get; set; } + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + string UpgradeType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.json.cs new file mode 100644 index 00000000000..74d177d6914 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunProperties.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The properties of the UpdateRun. + public partial class UpdateRunProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRunProperties(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._strategy ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._strategy.ToJson(null,serializationMode) : null, "strategy" ,container.Add ); + AddIf( null != this._managedClusterUpdate ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._managedClusterUpdate.ToJson(null,serializationMode) : null, "managedClusterUpdate" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AddIf( null != (((object)this._updateStrategyId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._updateStrategyId.ToString()) : null, "updateStrategyId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._autoUpgradeProfileId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._autoUpgradeProfileId.ToString()) : null, "autoUpgradeProfileId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRunProperties(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_strategy = If( json?.PropertyT("strategy"), out var __jsonStrategy) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStrategy.FromJson(__jsonStrategy) : _strategy;} + {_managedClusterUpdate = If( json?.PropertyT("managedClusterUpdate"), out var __jsonManagedClusterUpdate) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ManagedClusterUpdate.FromJson(__jsonManagedClusterUpdate) : _managedClusterUpdate;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunStatus.FromJson(__jsonStatus) : _status;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_updateStrategyId = If( json?.PropertyT("updateStrategyId"), out var __jsonUpdateStrategyId) ? (string)__jsonUpdateStrategyId : (string)_updateStrategyId;} + {_autoUpgradeProfileId = If( json?.PropertyT("autoUpgradeProfileId"), out var __jsonAutoUpgradeProfileId) ? (string)__jsonAutoUpgradeProfileId : (string)_autoUpgradeProfileId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.PowerShell.cs new file mode 100644 index 00000000000..9949eceee9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status of a UpdateRun. + [System.ComponentModel.TypeConverter(typeof(UpdateRunStatusTypeConverter))] + public partial class UpdateRunStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRunStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRunStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRunStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Stage = (System.Collections.Generic.List) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Stage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionSelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelectionSelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionSelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelectionSelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateRunStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("NodeImageSelection")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelection = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus) content.GetValueForProperty("NodeImageSelection",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelection, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Stage = (System.Collections.Generic.List) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Stage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("NodeImageSelectionSelectedNodeImageVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelectionSelectedNodeImageVersion = (System.Collections.Generic.List) content.GetValueForProperty("NodeImageSelectionSelectedNodeImageVersion",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).NodeImageSelectionSelectedNodeImageVersion, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageVersionTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The status of a UpdateRun. + [System.ComponentModel.TypeConverter(typeof(UpdateRunStatusTypeConverter))] + public partial interface IUpdateRunStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.TypeConverter.cs new file mode 100644 index 00000000000..02c6abe4084 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRunStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRunStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRunStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRunStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.cs new file mode 100644 index 00000000000..6ddfe88c839 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.cs @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a UpdateRun. + public partial class UpdateRunStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for NodeImageSelection + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.NodeImageSelection { get => (this._nodeImageSelection = this._nodeImageSelection ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatus()); set { {_nodeImageSelection = value;} } } + + /// Internal Acessors for NodeImageSelectionSelectedNodeImageVersion + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.NodeImageSelectionSelectedNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)NodeImageSelection).SelectedNodeImageVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)NodeImageSelection).SelectedNodeImageVersion = value ?? null /* arrayOf */; } + + /// Internal Acessors for Stage + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.Stage { get => this._stage; set { {_stage = value;} } } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error = value ?? null /* model class */; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatusInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus _nodeImageSelection; + + /// + /// The node image upgrade specs for the update run. It is only set in update run when `NodeImageSelection.type` is `Consistent`. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus NodeImageSelection { get => (this._nodeImageSelection = this._nodeImageSelection ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatus()); } + + /// The image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatusInternal)NodeImageSelection).SelectedNodeImageVersion; } + + /// Backing field for property. + private System.Collections.Generic.List _stage; + + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Stage { get => this._stage; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus _status; + + /// The status of the UpdateRun. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; } + + /// Creates an new instance. + public UpdateRunStatus() + { + + } + } + /// The status of a UpdateRun. + public partial interface IUpdateRunStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 image versions to upgrade the nodes to. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The image versions to upgrade the nodes to.", + SerializedName = @"selectedNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get; } + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The stages composing an update run. Stages are run sequentially withing an UpdateRun.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus) })] + System.Collections.Generic.List Stage { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 status of a UpdateRun. + internal partial interface IUpdateRunStatusInternal + + { + /// 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 node image upgrade specs for the update run. It is only set in update run when `NodeImageSelection.type` is `Consistent`. + /// + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageSelectionStatus NodeImageSelection { get; set; } + /// The image versions to upgrade the nodes to. + System.Collections.Generic.List NodeImageSelectionSelectedNodeImageVersion { get; set; } + /// + /// The stages composing an update run. Stages are run sequentially withing an UpdateRun. + /// + System.Collections.Generic.List Stage { get; set; } + /// The status of the UpdateRun. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.json.cs new file mode 100644 index 00000000000..84bd4ca88df --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStatus.json.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a UpdateRun. + public partial class UpdateRunStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRunStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._nodeImageSelection ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._nodeImageSelection.ToJson(null,serializationMode) : null, "nodeImageSelection" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._stage) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._stage ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("stages",__w); + } + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRunStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus.FromJson(__jsonStatus) : _status;} + {_nodeImageSelection = If( json?.PropertyT("nodeImageSelection"), out var __jsonNodeImageSelection) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.NodeImageSelectionStatus.FromJson(__jsonNodeImageSelection) : _nodeImageSelection;} + {_stage = If( json?.PropertyT("stages"), out var __jsonStages) ? If( __jsonStages as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateStageStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageStatus.FromJson(__u) )) ))() : null : _stage;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.PowerShell.cs new file mode 100644 index 00000000000..f55b03c1a2b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// Defines the update sequence of the clusters via stages and groups. + /// Stages within a run are executed sequentially one after another. + /// Groups within a stage are executed in parallel. + /// Member clusters within a group are updated sequentially one after another. + /// A valid strategy contains no duplicate groups within or across stages. + /// + [System.ComponentModel.TypeConverter(typeof(UpdateRunStrategyTypeConverter))] + public partial class UpdateRunStrategy + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateRunStrategy DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateRunStrategy(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateRunStrategy(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateRunStrategy(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)this).Stage = (System.Collections.Generic.List) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)this).Stage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateRunStrategy(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)this).Stage = (System.Collections.Generic.List) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal)this).Stage, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStageTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// Defines the update sequence of the clusters via stages and groups. + /// Stages within a run are executed sequentially one after another. + /// Groups within a stage are executed in parallel. + /// Member clusters within a group are updated sequentially one after another. + /// A valid strategy contains no duplicate groups within or across stages. + [System.ComponentModel.TypeConverter(typeof(UpdateRunStrategyTypeConverter))] + public partial interface IUpdateRunStrategy + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.TypeConverter.cs new file mode 100644 index 00000000000..524643ae145 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateRunStrategyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateRunStrategy ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateRunStrategy.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateRunStrategy.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateRunStrategy.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.cs new file mode 100644 index 00000000000..7bd6a3ac925 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Defines the update sequence of the clusters via stages and groups. + /// Stages within a run are executed sequentially one after another. + /// Groups within a stage are executed in parallel. + /// Member clusters within a group are updated sequentially one after another. + /// A valid strategy contains no duplicate groups within or across stages. + /// + public partial class UpdateRunStrategy : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategyInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _stage; + + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Stage { get => this._stage; set => this._stage = value; } + + /// Creates an new instance. + public UpdateRunStrategy() + { + + } + } + /// Defines the update sequence of the clusters via stages and groups. + /// Stages within a run are executed sequentially one after another. + /// Groups within a stage are executed in parallel. + /// Member clusters within a group are updated sequentially one after another. + /// A valid strategy contains no duplicate groups within or across stages. + public partial interface IUpdateRunStrategy : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The list of stages that compose this update run. Min size: 1. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + System.Collections.Generic.List Stage { get; set; } + + } + /// Defines the update sequence of the clusters via stages and groups. + /// Stages within a run are executed sequentially one after another. + /// Groups within a stage are executed in parallel. + /// Member clusters within a group are updated sequentially one after another. + /// A valid strategy contains no duplicate groups within or across stages. + internal partial interface IUpdateRunStrategyInternal + + { + /// The list of stages that compose this update run. Min size: 1. + System.Collections.Generic.List Stage { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.json.cs new file mode 100644 index 00000000000..cebe3fe8f28 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateRunStrategy.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Defines the update sequence of the clusters via stages and groups. + /// Stages within a run are executed sequentially one after another. + /// Groups within a stage are executed in parallel. + /// Member clusters within a group are updated sequentially one after another. + /// A valid strategy contains no duplicate groups within or across stages. + /// + public partial class UpdateRunStrategy + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunStrategy FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateRunStrategy(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._stage) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._stage ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("stages",__w); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateRunStrategy(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_stage = If( json?.PropertyT("stages"), out var __jsonStages) ? If( __jsonStages as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateStage) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStage.FromJson(__u) )) ))() : null : _stage;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.PowerShell.cs new file mode 100644 index 00000000000..7106d8ec02b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.PowerShell.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting + /// the next stage. + /// + [System.ComponentModel.TypeConverter(typeof(UpdateStageTypeConverter))] + public partial class UpdateStage + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateStage DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateStage(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateStage(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateStage(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.ContainerServiceFleet.Models.IUpdateStageInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).Group = (System.Collections.Generic.List) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).Group, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateGroupTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterStageWaitInSecond")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterStageWaitInSecond = (int?) content.GetValueForProperty("AfterStageWaitInSecond",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterStageWaitInSecond, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateStage(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.ContainerServiceFleet.Models.IUpdateStageInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).Group = (System.Collections.Generic.List) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).Group, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateGroupTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterStageWaitInSecond")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterStageWaitInSecond = (int?) content.GetValueForProperty("AfterStageWaitInSecond",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterStageWaitInSecond, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfigurationTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting + /// the next stage. + [System.ComponentModel.TypeConverter(typeof(UpdateStageTypeConverter))] + public partial interface IUpdateStage + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.TypeConverter.cs new file mode 100644 index 00000000000..377c4379f4f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateStageTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateStage ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateStage.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateStage.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateStage.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateStage.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.cs new file mode 100644 index 00000000000..1ad86377f59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting + /// the next stage. + /// + public partial class UpdateStage : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _afterGate; + + /// A list of Gates that will be created after this Stage is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List AfterGate { get => this._afterGate; set => this._afterGate = value; } + + /// Backing field for property. + private int? _afterStageWaitInSecond; + + /// + /// The time in seconds to wait at the end of this stage before starting the next one. Defaults to 0 seconds if unspecified. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public int? AfterStageWaitInSecond { get => this._afterStageWaitInSecond; set => this._afterStageWaitInSecond = value; } + + /// Backing field for property. + private System.Collections.Generic.List _beforeGate; + + /// A list of Gates that will be created before this Stage is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List BeforeGate { get => this._beforeGate; set => this._beforeGate = value; } + + /// Backing field for property. + private System.Collections.Generic.List _group; + + /// + /// Defines the groups to be executed in parallel in this stage. Duplicate groups are not allowed. Min size: 1. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Group { get => this._group; set => this._group = value; } + + /// Backing field for property. + private string _name; + + /// The name of the stage. Must be unique within the UpdateRun. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public UpdateStage() + { + + } + } + /// Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting + /// the next stage. + public partial interface IUpdateStage : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// A list of Gates that will be created after this Stage is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A list of Gates that will be created after this Stage is executed.", + SerializedName = @"afterGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration) })] + System.Collections.Generic.List AfterGate { get; set; } + /// + /// The time in seconds to wait at the end of this stage before starting the next one. Defaults to 0 seconds if unspecified. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The time in seconds to wait at the end of this stage before starting the next one. Defaults to 0 seconds if unspecified.", + SerializedName = @"afterStageWaitInSeconds", + PossibleTypes = new [] { typeof(int) })] + int? AfterStageWaitInSecond { get; set; } + /// A list of Gates that will be created before this Stage is executed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A list of Gates that will be created before this Stage is executed.", + SerializedName = @"beforeGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration) })] + System.Collections.Generic.List BeforeGate { get; set; } + /// + /// Defines the groups to be executed in parallel in this stage. Duplicate groups are not allowed. Min size: 1. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Defines the groups to be executed in parallel in this stage. Duplicate groups are not allowed. Min size: 1.", + SerializedName = @"groups", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroup) })] + System.Collections.Generic.List Group { get; set; } + /// The name of the stage. Must be unique within the UpdateRun. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The name of the stage. Must be unique within the UpdateRun.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting + /// the next stage. + internal partial interface IUpdateStageInternal + + { + /// A list of Gates that will be created after this Stage is executed. + System.Collections.Generic.List AfterGate { get; set; } + /// + /// The time in seconds to wait at the end of this stage before starting the next one. Defaults to 0 seconds if unspecified. + /// + int? AfterStageWaitInSecond { get; set; } + /// A list of Gates that will be created before this Stage is executed. + System.Collections.Generic.List BeforeGate { get; set; } + /// + /// Defines the groups to be executed in parallel in this stage. Duplicate groups are not allowed. Min size: 1. + /// + System.Collections.Generic.List Group { get; set; } + /// The name of the stage. Must be unique within the UpdateRun. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.json.cs new file mode 100644 index 00000000000..a424dace9f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStage.json.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// + /// Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting + /// the next stage. + /// + public partial class UpdateStage + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateStage(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + if (null != this._group) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._group ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("groups",__w); + } + AddIf( null != this._afterStageWaitInSecond ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNumber((int)this._afterStageWaitInSecond) : null, "afterStageWaitInSeconds" ,container.Add ); + if (null != this._beforeGate) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __s in this._beforeGate ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("beforeGates",__r); + } + if (null != this._afterGate) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __n in this._afterGate ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("afterGates",__m); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateStage(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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;} + {_group = If( json?.PropertyT("groups"), out var __jsonGroups) ? If( __jsonGroups as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateGroup) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateGroup.FromJson(__u) )) ))() : null : _group;} + {_afterStageWaitInSecond = If( json?.PropertyT("afterStageWaitInSeconds"), out var __jsonAfterStageWaitInSeconds) ? (int?)__jsonAfterStageWaitInSeconds : _afterStageWaitInSecond;} + {_beforeGate = If( json?.PropertyT("beforeGates"), out var __jsonBeforeGates) ? If( __jsonBeforeGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGateConfiguration) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfiguration.FromJson(__p) )) ))() : null : _beforeGate;} + {_afterGate = If( json?.PropertyT("afterGates"), out var __jsonAfterGates) ? If( __jsonAfterGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGateConfiguration) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GateConfiguration.FromJson(__k) )) ))() : null : _afterGate;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.PowerShell.cs new file mode 100644 index 00000000000..aff804b7523 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.PowerShell.cs @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status of a UpdateStage. + [System.ComponentModel.TypeConverter(typeof(UpdateStageStatusTypeConverter))] + public partial class UpdateStageStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateStageStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateStageStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateStageStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateStageStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("AfterStageWaitStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus) content.GetValueForProperty("AfterStageWaitStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.WaitStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Group = (System.Collections.Generic.List) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Group, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateGroupStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).CompletedTime = (global::System.DateTime?) content.GetValueForProperty("CompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).CompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("AfterStageWaitStatusStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("AfterStageWaitStatusWaitDurationInSecond")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusWaitDurationInSecond = (int?) content.GetValueForProperty("AfterStageWaitStatusWaitDurationInSecond",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusWaitDurationInSecond, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("StatusErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorCode = (string) content.GetValueForProperty("StatusErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorCode, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorMessage = (string) content.GetValueForProperty("StatusErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorTarget = (string) content.GetValueForProperty("StatusErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("StatusErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("StatusErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterStageWaitStatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("AfterStageWaitStatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("AfterStageWaitStatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStartTime = (global::System.DateTime?) content.GetValueForProperty("AfterStageWaitStatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AfterStageWaitStatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("AfterStageWaitStatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AfterStageWaitStatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusState = (string) content.GetValueForProperty("AfterStageWaitStatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusState, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorCode = (string) content.GetValueForProperty("AfterStageWaitStatusErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorCode, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorMessage = (string) content.GetValueForProperty("AfterStageWaitStatusErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorTarget = (string) content.GetValueForProperty("AfterStageWaitStatusErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("AfterStageWaitStatusErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterStageWaitStatusErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AfterStageWaitStatusErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateStageStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("AfterStageWaitStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus) content.GetValueForProperty("AfterStageWaitStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.WaitStatusTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Group")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Group = (System.Collections.Generic.List) content.GetValueForProperty("Group",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Group, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateGroupStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("BeforeGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).BeforeGate = (System.Collections.Generic.List) content.GetValueForProperty("BeforeGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).BeforeGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterGate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterGate = (System.Collections.Generic.List) content.GetValueForProperty("AfterGate",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterGate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatusTypeConverter.ConvertFrom)); + } + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).CompletedTime = (global::System.DateTime?) content.GetValueForProperty("CompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).CompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStatus = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("AfterStageWaitStatusStatus",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStatus, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("AfterStageWaitStatusWaitDurationInSecond")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusWaitDurationInSecond = (int?) content.GetValueForProperty("AfterStageWaitStatusWaitDurationInSecond",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusWaitDurationInSecond, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("StatusErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorCode = (string) content.GetValueForProperty("StatusErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorCode, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorMessage = (string) content.GetValueForProperty("StatusErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorTarget = (string) content.GetValueForProperty("StatusErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("StatusErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("StatusErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("StatusErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("StatusErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).StatusErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterStageWaitStatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("AfterStageWaitStatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("AfterStageWaitStatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStartTime = (global::System.DateTime?) content.GetValueForProperty("AfterStageWaitStatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AfterStageWaitStatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("AfterStageWaitStatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("AfterStageWaitStatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusState = (string) content.GetValueForProperty("AfterStageWaitStatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusState, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorCode = (string) content.GetValueForProperty("AfterStageWaitStatusErrorCode",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorCode, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorMessage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorMessage = (string) content.GetValueForProperty("AfterStageWaitStatusErrorMessage",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorMessage, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorTarget")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorTarget = (string) content.GetValueForProperty("AfterStageWaitStatusErrorTarget",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorTarget, global::System.Convert.ToString); + } + if (content.Contains("AfterStageWaitStatusErrorDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorDetail = (System.Collections.Generic.List) content.GetValueForProperty("AfterStageWaitStatusErrorDetail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorDetail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AfterStageWaitStatusErrorAdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorAdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AfterStageWaitStatusErrorAdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal)this).AfterStageWaitStatusErrorAdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The status of a UpdateStage. + [System.ComponentModel.TypeConverter(typeof(UpdateStageStatusTypeConverter))] + public partial interface IUpdateStageStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.TypeConverter.cs new file mode 100644 index 00000000000..b3258dda7ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateStageStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateStageStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateStageStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateStageStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateStageStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.cs new file mode 100644 index 00000000000..0bf372a5ee7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.cs @@ -0,0 +1,507 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a UpdateStage. + public partial class UpdateStageStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _afterGate; + + /// The list of Gates that will run after this UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List AfterGate { get => this._afterGate; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus _afterStageWaitStatus; + + /// The status of the wait period configured on the UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus AfterStageWaitStatus { get => (this._afterStageWaitStatus = this._afterStageWaitStatus ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.WaitStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? AfterStageWaitStatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusCompletedTime; } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AfterStageWaitStatusErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AfterStageWaitStatusErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AfterStageWaitStatusErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AfterStageWaitStatusErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Message; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AfterStageWaitStatusErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Target; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? AfterStageWaitStatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusStartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string AfterStageWaitStatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusState; } + + /// The wait duration configured in seconds. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public int? AfterStageWaitStatusWaitDurationInSecond { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).WaitDurationInSecond; } + + /// Backing field for property. + private System.Collections.Generic.List _beforeGate; + + /// The list of Gates that will run before this UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List BeforeGate { get => this._beforeGate; } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? CompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; } + + /// Backing field for property. + private System.Collections.Generic.List _group; + + /// The list of groups to be updated as part of this UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public System.Collections.Generic.List Group { get => this._group; } + + /// Internal Acessors for AfterGate + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterGate { get => this._afterGate; set { {_afterGate = value;} } } + + /// Internal Acessors for AfterStageWaitStatus + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatus { get => (this._afterStageWaitStatus = this._afterStageWaitStatus ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.WaitStatus()); set { {_afterStageWaitStatus = value;} } } + + /// Internal Acessors for AfterStageWaitStatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusCompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusCompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for AfterStageWaitStatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusError; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusError = value ?? null /* model class */; } + + /// Internal Acessors for AfterStageWaitStatusErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for AfterStageWaitStatusErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Code = value ?? null; } + + /// Internal Acessors for AfterStageWaitStatusErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for AfterStageWaitStatusErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Message = value ?? null; } + + /// Internal Acessors for AfterStageWaitStatusErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Target = value ?? null; } + + /// Internal Acessors for AfterStageWaitStatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusStartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusStartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for AfterStageWaitStatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).StatusState = value ?? null; } + + /// Internal Acessors for AfterStageWaitStatusStatus + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).Status = value ?? null /* model class */; } + + /// Internal Acessors for AfterStageWaitStatusWaitDurationInSecond + int? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.AfterStageWaitStatusWaitDurationInSecond { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).WaitDurationInSecond; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)AfterStageWaitStatus).WaitDurationInSecond = value ?? default(int); } + + /// Internal Acessors for BeforeGate + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.BeforeGate { get => this._beforeGate; set { {_beforeGate = value;} } } + + /// Internal Acessors for CompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.CompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.Error { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error = value ?? null /* model class */; } + + /// Internal Acessors for Group + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.Group { get => this._group; set { {_group = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.StartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.State { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusErrorAdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.StatusErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for StatusErrorCode + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.StatusErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for StatusErrorDetail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.StatusErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for StatusErrorMessage + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.StatusErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for StatusErrorTarget + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatusInternal.StatusErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target = value ?? null; } + + /// Backing field for property. + private string _name; + + /// The name of the UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string State { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus _status; + + /// The status of the UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); } + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StatusErrorAdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusErrorCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List StatusErrorDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusErrorMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusErrorTarget { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; } + + /// Creates an new instance. + public UpdateStageStatus() + { + + } + } + /// The status of a UpdateStage. + public partial interface IUpdateStageStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The list of Gates that will run after this UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The list of Gates that will run after this UpdateStage.", + SerializedName = @"afterGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus) })] + System.Collections.Generic.List AfterGate { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? AfterStageWaitStatusCompletedTime { get; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AfterStageWaitStatusErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string AfterStageWaitStatusErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List AfterStageWaitStatusErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string AfterStageWaitStatusErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string AfterStageWaitStatusErrorTarget { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? AfterStageWaitStatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string AfterStageWaitStatusState { get; } + /// The wait duration configured in seconds. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The wait duration configured in seconds.", + SerializedName = @"waitDurationInSeconds", + PossibleTypes = new [] { typeof(int) })] + int? AfterStageWaitStatusWaitDurationInSecond { get; } + /// The list of Gates that will run before this UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The list of Gates that will run before this UpdateStage.", + SerializedName = @"beforeGates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus) })] + System.Collections.Generic.List BeforeGate { get; } + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CompletedTime { get; } + /// The list of groups to be updated as part of this UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The list of groups to be updated as part of this UpdateStage.", + SerializedName = @"groups", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateGroupStatus) })] + System.Collections.Generic.List Group { get; } + /// The name of the UpdateStage. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the UpdateStage.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string State { get; } + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List StatusErrorAdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string StatusErrorCode { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List StatusErrorDetail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string StatusErrorMessage { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string StatusErrorTarget { get; } + + } + /// The status of a UpdateStage. + internal partial interface IUpdateStageStatusInternal + + { + /// The list of Gates that will run after this UpdateStage. + System.Collections.Generic.List AfterGate { get; set; } + /// The status of the wait period configured on the UpdateStage. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus AfterStageWaitStatus { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? AfterStageWaitStatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail AfterStageWaitStatusError { get; set; } + /// The error additional info. + System.Collections.Generic.List AfterStageWaitStatusErrorAdditionalInfo { get; set; } + /// The error code. + string AfterStageWaitStatusErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List AfterStageWaitStatusErrorDetail { get; set; } + /// The error message. + string AfterStageWaitStatusErrorMessage { get; set; } + /// The error target. + string AfterStageWaitStatusErrorTarget { get; set; } + /// The time the operation or group was started. + global::System.DateTime? AfterStageWaitStatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string AfterStageWaitStatusState { get; set; } + /// The status of the wait duration. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus AfterStageWaitStatusStatus { get; set; } + /// The wait duration configured in seconds. + int? AfterStageWaitStatusWaitDurationInSecond { get; set; } + /// The list of Gates that will run before this UpdateStage. + System.Collections.Generic.List BeforeGate { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? CompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Error { get; set; } + /// The list of groups to be updated as part of this UpdateStage. + System.Collections.Generic.List Group { get; set; } + /// The name of the UpdateStage. + string Name { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string State { get; set; } + /// The status of the UpdateStage. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get; set; } + /// The error additional info. + System.Collections.Generic.List StatusErrorAdditionalInfo { get; set; } + /// The error code. + string StatusErrorCode { get; set; } + /// The error details. + System.Collections.Generic.List StatusErrorDetail { get; set; } + /// The error message. + string StatusErrorMessage { get; set; } + /// The error target. + string StatusErrorTarget { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.json.cs new file mode 100644 index 00000000000..2a296e838cd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStageStatus.json.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of a UpdateStage. + public partial class UpdateStageStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStageStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateStageStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._afterStageWaitStatus ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._afterStageWaitStatus.ToJson(null,serializationMode) : null, "afterStageWaitStatus" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._group) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __x in this._group ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("groups",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._beforeGate) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __s in this._beforeGate ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("beforeGates",__r); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._afterGate) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.XNodeArray(); + foreach( var __n in this._afterGate ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("afterGates",__m); + } + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateStageStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus.FromJson(__jsonStatus) : _status;} + {_afterStageWaitStatus = If( json?.PropertyT("afterStageWaitStatus"), out var __jsonAfterStageWaitStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.WaitStatus.FromJson(__jsonAfterStageWaitStatus) : _afterStageWaitStatus;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_group = If( json?.PropertyT("groups"), out var __jsonGroups) ? If( __jsonGroups as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateGroupStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateGroupStatus.FromJson(__u) )) ))() : null : _group;} + {_beforeGate = If( json?.PropertyT("beforeGates"), out var __jsonBeforeGates) ? If( __jsonBeforeGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRunGateStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatus.FromJson(__p) )) ))() : null : _beforeGate;} + {_afterGate = If( json?.PropertyT("afterGates"), out var __jsonAfterGates) ? If( __jsonAfterGates as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonArray, out var __l) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRunGateStatus) (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRunGateStatus.FromJson(__k) )) ))() : null : _afterGate;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.PowerShell.cs new file mode 100644 index 00000000000..dbdc4be59a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status for an operation or group of operations. + [System.ComponentModel.TypeConverter(typeof(UpdateStatusTypeConverter))] + public partial class UpdateStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IUpdateStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UpdateStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UpdateStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 UpdateStatus(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.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).CompletedTime = (global::System.DateTime?) content.GetValueForProperty("CompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).CompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UpdateStatus(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.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).StartTime = (global::System.DateTime?) content.GetValueForProperty("StartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).StartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).CompletedTime = (global::System.DateTime?) content.GetValueForProperty("CompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).CompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The status for an operation or group of operations. + [System.ComponentModel.TypeConverter(typeof(UpdateStatusTypeConverter))] + public partial interface IUpdateStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.TypeConverter.cs new file mode 100644 index 00000000000..9d350daee62 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UpdateStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUpdateStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UpdateStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UpdateStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UpdateStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.cs new file mode 100644 index 00000000000..9e6f93a41d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status for an operation or group of operations. + public partial class UpdateStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Code; } + + /// Backing field for property. + private global::System.DateTime? _completedTime; + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public global::System.DateTime? CompletedTime { get => this._completedTime; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail _error; + + /// The error details when a failure is encountered. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Code = value ?? null; } + + /// Internal Acessors for CompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.CompletedTime { get => this._completedTime; set { {_completedTime = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Message = value ?? null; } + + /// Internal Acessors for StartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.StartTime { get => this._startTime; set { {_startTime = value;} } } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.State { get => this._state; set { {_state = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Target = value ?? null; } + + /// Backing field for property. + private global::System.DateTime? _startTime; + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public global::System.DateTime? StartTime { get => this._startTime; } + + /// Backing field for property. + private string _state; + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string State { get => this._state; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public UpdateStatus() + { + + } + } + /// The status for an operation or group of operations. + public partial interface IUpdateStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CompletedTime { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string State { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 status for an operation or group of operations. + internal partial interface IUpdateStatusInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? CompletedTime { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Error { get; set; } + /// The error message. + string Message { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string State { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.json.cs new file mode 100644 index 00000000000..b145e723f68 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UpdateStatus.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status for an operation or group of operations. + public partial class UpdateStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new UpdateStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._error.ToJson(null,serializationMode) : null, "error" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._startTime ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._startTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "startTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._completedTime ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._completedTime?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "completedTime" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UpdateStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.ErrorDetail.FromJson(__jsonError) : _error;} + {_startTime = If( json?.PropertyT("startTime"), out var __jsonStartTime) ? global::System.DateTime.TryParse((string)__jsonStartTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonStartTimeValue) ? __jsonStartTimeValue : _startTime : _startTime;} + {_completedTime = If( json?.PropertyT("completedTime"), out var __jsonCompletedTime) ? global::System.DateTime.TryParse((string)__jsonCompletedTime, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCompletedTimeValue) ? __jsonCompletedTimeValue : _completedTime : _completedTime;} + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs new file mode 100644 index 00000000000..989805d33e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUserAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs new file mode 100644 index 00000000000..6e5117f2a62 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IUserAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.cs new file mode 100644 index 00000000000..e2229e6257c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentityInternal + { + + /// Backing field for property. + private string _clientId; + + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentityInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/UserAssignedIdentity.json.cs new file mode 100644 index 00000000000..440ea0103e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUserAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/api/Models/WaitStatus.PowerShell.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.PowerShell.cs new file mode 100644 index 00000000000..3743073284d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// The status of the wait duration. + [System.ComponentModel.TypeConverter(typeof(WaitStatusTypeConverter))] + public partial class WaitStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of 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.ContainerServiceFleet.Models.IWaitStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new WaitStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new WaitStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 WaitStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("WaitDurationInSecond")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).WaitDurationInSecond = (int?) content.GetValueForProperty("WaitDurationInSecond",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).WaitDurationInSecond, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal WaitStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Status = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Status, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatusTypeConverter.ConvertFrom); + } + if (content.Contains("WaitDurationInSecond")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).WaitDurationInSecond = (int?) content.GetValueForProperty("WaitDurationInSecond",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).WaitDurationInSecond, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("StatusError")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusError = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail) content.GetValueForProperty("StatusError",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusError, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("StatusStartTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusStartTime = (global::System.DateTime?) content.GetValueForProperty("StatusStartTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusCompletedTime")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusCompletedTime = (global::System.DateTime?) content.GetValueForProperty("StatusCompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusCompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("StatusState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusState = (string) content.GetValueForProperty("StatusState",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).StatusState, global::System.Convert.ToString); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + } + /// The status of the wait duration. + [System.ComponentModel.TypeConverter(typeof(WaitStatusTypeConverter))] + public partial interface IWaitStatus + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.TypeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.TypeConverter.cs new file mode 100644 index 00000000000..5ddf78c29d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.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.ContainerServiceFleet.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class WaitStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, 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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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.ContainerServiceFleet.Models.IWaitStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return WaitStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return WaitStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return WaitStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override 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/Fleet.Management.brown/target/generated/api/Models/WaitStatus.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.cs new file mode 100644 index 00000000000..bcad5a661db --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of the wait duration. + public partial class WaitStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).AdditionalInfo = value ?? null /* arrayOf */; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Code = value ?? null; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Detail = value ?? null /* arrayOf */; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Message = value ?? null; } + + /// Internal Acessors for Status + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); set { {_status = value;} } } + + /// Internal Acessors for StatusCompletedTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusError + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.StatusError { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Error = value ?? null /* model class */; } + + /// Internal Acessors for StatusStartTime + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime = value ?? default(global::System.DateTime); } + + /// Internal Acessors for StatusState + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State = value ?? null; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target = value ?? null; } + + /// Internal Acessors for WaitDurationInSecond + int? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatusInternal.WaitDurationInSecond { get => this._waitDurationInSecond; set { {_waitDurationInSecond = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus _status; + + /// The status of the wait duration. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get => (this._status = this._status ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus()); } + + /// The time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusCompletedTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).CompletedTime; } + + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public global::System.DateTime? StatusStartTime { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).StartTime; } + + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string StatusState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).State; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatusInternal)Status).Target; } + + /// Backing field for property. + private int? _waitDurationInSecond; + + /// The wait duration configured in seconds. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Origin(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PropertyOrigin.Owned)] + public int? WaitDurationInSecond { get => this._waitDurationInSecond; } + + /// Creates an new instance. + public WaitStatus() + { + + } + } + /// The status of the wait duration. + public partial interface IWaitStatus : + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 time the operation or group was completed. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was completed.", + SerializedName = @"completedTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusCompletedTime { get; } + /// The time the operation or group was started. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The time the operation or group was started.", + SerializedName = @"startTime", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? StatusStartTime { get; } + /// The State of the operation or group. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The State of the operation or group.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 wait duration configured in seconds. + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The wait duration configured in seconds.", + SerializedName = @"waitDurationInSeconds", + PossibleTypes = new [] { typeof(int) })] + int? WaitDurationInSecond { get; } + + } + /// The status of the wait duration. + internal partial interface IWaitStatusInternal + + { + /// 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 status of the wait duration. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStatus Status { get; set; } + /// The time the operation or group was completed. + global::System.DateTime? StatusCompletedTime { get; set; } + /// The error details when a failure is encountered. + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IErrorDetail StatusError { get; set; } + /// The time the operation or group was started. + global::System.DateTime? StatusStartTime { get; set; } + /// The State of the operation or group. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("NotStarted", "Running", "Stopping", "Stopped", "Skipped", "Failed", "Pending", "Completed")] + string StatusState { get; set; } + /// The error target. + string Target { get; set; } + /// The wait duration configured in seconds. + int? WaitDurationInSecond { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.json.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.json.cs new file mode 100644 index 00000000000..276986932d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/api/Models/WaitStatus.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.ContainerServiceFleet.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + + /// The status of the wait duration. + public partial class WaitStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the + /// output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IWaitStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json ? new WaitStatus(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.ContainerServiceFleet.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._status ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode) this._status.ToJson(null,serializationMode) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._waitDurationInSecond ? (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonNumber((int)this._waitDurationInSecond) : null, "waitDurationInSeconds" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject instance to deserialize from. + internal WaitStatus(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateStatus.FromJson(__jsonStatus) : _status;} + {_waitDurationInSecond = If( json?.PropertyT("waitDurationInSeconds"), out var __jsonWaitDurationInSeconds) ? (int?)__jsonWaitDurationInSeconds : _waitDurationInSecond;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_Get.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_Get.cs new file mode 100644 index 00000000000..d76c30ad1d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_Get.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a AutoUpgradeProfile + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetAutoUpgradeProfile_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetAutoUpgradeProfile_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetAutoUpgradeProfile_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesGet(SubscriptionId, ResourceGroupName, FleetName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentity.cs new file mode 100644 index 00000000000..9cd42f2d794 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a AutoUpgradeProfile + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetAutoUpgradeProfile_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetAutoUpgradeProfile_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.AutoUpgradeProfilesGetViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.AutoUpgradeProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AutoUpgradeProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.AutoUpgradeProfilesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.AutoUpgradeProfileName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentityFleet.cs new file mode 100644 index 00000000000..8cfbb4ee4df --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentityFleet.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a AutoUpgradeProfile + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetAutoUpgradeProfile_GetViaIdentityFleet")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetAutoUpgradeProfile_GetViaIdentityFleet() + { + + } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/autoUpgradeProfiles/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.AutoUpgradeProfilesGetViaIdentity(FleetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.AutoUpgradeProfilesGet(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_List.cs new file mode 100644 index 00000000000..46865ed4451 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetAutoUpgradeProfile_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// List AutoUpgradeProfile resources by Fleet + /// + /// [OpenAPI] ListByFleet=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetAutoUpgradeProfile_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"List AutoUpgradeProfile resources by Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetAutoUpgradeProfile_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetAutoUpgradeProfile_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesListByFleet(SubscriptionId, ResourceGroupName, FleetName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfileListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesListByFleet_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetCredentials_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetCredentials_List.cs new file mode 100644 index 00000000000..1a8478c4d14 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetCredentials_List.cs @@ -0,0 +1,515 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Lists the user credentials of a Fleet. + /// + /// [OpenAPI] ListCredentials=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/listCredentials" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetCredentials_List", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetCredentialResults))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Lists the user credentials of a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/listCredentials", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetCredentials_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetCredentialResults + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetCredentials_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsListCredentials' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsListCredentials(SubscriptionId, ResourceGroupName, FleetName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetCredentialResults + /// 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.ContainerServiceFleet.Models.IFleetCredentialResults + var result = (await response); + // response should be returning an array of some kind. +Pageable + // nested-array / kubeconfigs / + if (null != result.Kubeconfig) + { + if (0 == _responseSize && 1 == result.Kubeconfig.Count) + { + _firstResponse = result.Kubeconfig[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Kubeconfig ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_Get.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_Get.cs new file mode 100644 index 00000000000..5922492d7ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_Get.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a Gate + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetGate_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetGate_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Gate resource, a GUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Gate resource, a GUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("GateName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetGate_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GatesGet(SubscriptionId, ResourceGroupName, FleetName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_GetViaIdentity.cs new file mode 100644 index 00000000000..0a297db7f64 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a Gate + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetGate_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetGate_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetGate_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.GatesGetViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.GateName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.GateName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.GatesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.GateName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_GetViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_GetViaIdentityFleet.cs new file mode 100644 index 00000000000..147ca85192b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_GetViaIdentityFleet.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a Gate + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetGate_GetViaIdentityFleet")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetGate_GetViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Gate resource, a GUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Gate resource, a GUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("GateName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetGate_GetViaIdentityFleet() + { + + } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/gates/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.GatesGetViaIdentity(FleetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.GatesGet(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_List.cs new file mode 100644 index 00000000000..749ed29ddb3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetGate_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// List Gate resources by Fleet + /// + /// [OpenAPI] ListByFleet=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetGate_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"List Gate resources by Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetGate_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGateListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetGate_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GatesListByFleet(SubscriptionId, ResourceGroupName, FleetName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGateListResult + /// 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.ContainerServiceFleet.Models.IGateListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GatesListByFleet_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_Get.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_Get.cs new file mode 100644 index 00000000000..ebb30373530 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_Get.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a FleetMember + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetMember_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetMember_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetMember_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersGet(SubscriptionId, ResourceGroupName, FleetName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_GetViaIdentity.cs new file mode 100644 index 00000000000..4f43b22bd6e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a FleetMember + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetMember_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetMember_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetMember_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetMembersGetViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetMemberName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetMemberName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetMembersGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.FleetMemberName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_GetViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_GetViaIdentityFleet.cs new file mode 100644 index 00000000000..24103273d01 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_GetViaIdentityFleet.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a FleetMember + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetMember_GetViaIdentityFleet")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetMember_GetViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetMember_GetViaIdentityFleet() + { + + } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/members/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.FleetMembersGetViaIdentity(FleetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.FleetMembersGet(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_List.cs new file mode 100644 index 00000000000..2585fb72793 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetMember_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// List FleetMember resources by Fleet + /// + /// [OpenAPI] ListByFleet=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetMember_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"List FleetMember resources by Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetMember_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMemberListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetMember_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersListByFleet(SubscriptionId, ResourceGroupName, FleetName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMemberListResult + /// 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.ContainerServiceFleet.Models.IFleetMemberListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersListByFleet_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetOperation_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetOperation_List.cs new file mode 100644 index 00000000000..4fa8bd4908b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetOperation_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Microsoft.ContainerService/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/providers/Microsoft.ContainerService/operations", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetOperation_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_Get.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_Get.cs new file mode 100644 index 00000000000..4a94d9dbd92 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_Get.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a UpdateRun + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateRun_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateRun_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsGet(SubscriptionId, ResourceGroupName, FleetName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_GetViaIdentity.cs new file mode 100644 index 00000000000..9a44cf4841c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a UpdateRun + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateRun_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateRun_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UpdateRunsGetViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UpdateRunsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_GetViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_GetViaIdentityFleet.cs new file mode 100644 index 00000000000..087766ef563 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_GetViaIdentityFleet.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a UpdateRun + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateRun_GetViaIdentityFleet")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateRun_GetViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateRun_GetViaIdentityFleet() + { + + } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.UpdateRunsGetViaIdentity(FleetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.UpdateRunsGet(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_List.cs new file mode 100644 index 00000000000..7be2be4c0d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// List UpdateRun resources by Fleet + /// + /// [OpenAPI] ListByFleet=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateRun_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"List UpdateRun resources by Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateRun_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRunListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsListByFleet(SubscriptionId, ResourceGroupName, FleetName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRunListResult + /// 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.ContainerServiceFleet.Models.IUpdateRunListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsListByFleet_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_Get.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_Get.cs new file mode 100644 index 00000000000..d8d9cd40883 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a FleetUpdateStrategy + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateStrategy_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateStrategy_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesGet(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_GetViaIdentity.cs new file mode 100644 index 00000000000..e36a94ef4bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a FleetUpdateStrategy + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateStrategy_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateStrategy_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetUpdateStrategiesGetViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateStrategyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateStrategyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetUpdateStrategiesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateStrategyName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_GetViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_GetViaIdentityFleet.cs new file mode 100644 index 00000000000..72c3b24b2c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_GetViaIdentityFleet.cs @@ -0,0 +1,498 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Get a FleetUpdateStrategy + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateStrategy_GetViaIdentityFleet")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Get a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateStrategy_GetViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateStrategy_GetViaIdentityFleet() + { + + } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateStrategies/{(global::System.Uri.EscapeDataString(this.UpdateStrategyName.ToString()))}"; + await this.Client.FleetUpdateStrategiesGetViaIdentity(FleetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.FleetUpdateStrategiesGet(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, UpdateStrategyName, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_List.cs new file mode 100644 index 00000000000..289f4b1f780 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// List FleetUpdateStrategy resources by Fleet + /// + /// [OpenAPI] ListByFleet=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleetUpdateStrategy_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"List FleetUpdateStrategy resources by Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleetUpdateStrategy_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesListByFleet(SubscriptionId, ResourceGroupName, FleetName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategyListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesListByFleet_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_Get.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_Get.cs new file mode 100644 index 00000000000..f185120238d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Gets a Fleet. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleet_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Gets a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleet_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleet_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_GetViaIdentity.cs new file mode 100644 index 00000000000..6304234084b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Gets a Fleet. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleet_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Gets a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleet_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleet_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetsGetViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + 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/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_List.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_List.cs new file mode 100644 index 00000000000..d4cc7003b14 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Lists fleets in the specified subscription and resource group. + /// + /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleet_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Lists fleets in the specified subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleet_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleet_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetListResult + /// 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.ContainerServiceFleet.Models.IFleetListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_List1.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_List1.cs new file mode 100644 index 00000000000..7c6c0b0a357 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/GetAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Lists fleets in the specified subscription. + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/fleets" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzContainerServiceFleet_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Lists fleets in the specified subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/fleets", ApiVersion = "2025-04-01-preview")] + public partial class GetAzContainerServiceFleet_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetListResult + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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 GetAzContainerServiceFleet_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetListResult + /// 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.ContainerServiceFleet.Models.IFleetListResult + 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.ContainerServiceFleet.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate.cs new file mode 100644 index 00000000000..71e5657737e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate.cs @@ -0,0 +1,574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Generates an generate run for a given auto upgrade profile. + /// + /// [OpenAPI] GenerateUpdateRun=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}/generateUpdateRun" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Generates an generate run for a given auto upgrade profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}/generateUpdateRun", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private string _autoUpgradeProfileName; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string AutoUpgradeProfileName { get => this._autoUpgradeProfileName; set => this._autoUpgradeProfileName = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGenerateResponse + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate Clone() + { + var clone = new NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate(); + 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.FleetName = this.FleetName; + clone.AutoUpgradeProfileName = this.AutoUpgradeProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_Generate() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfileOperationsGenerateUpdateRun' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfileOperationsGenerateUpdateRun(SubscriptionId, ResourceGroupName, FleetName, AutoUpgradeProfileName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,FleetName=FleetName,AutoUpgradeProfileName=AutoUpgradeProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGenerateResponse + /// 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.ContainerServiceFleet.Models.IGenerateResponse + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity.cs new file mode 100644 index 00000000000..fd2fc2d0c03 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Generates an generate run for a given auto upgrade profile. + /// + /// [OpenAPI] GenerateUpdateRun=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}/generateUpdateRun" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Generates an generate run for a given auto upgrade profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}/generateUpdateRun", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGenerateResponse + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity Clone() + { + var clone = new NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity(); + 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() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentity() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfileOperationsGenerateUpdateRun' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.AutoUpgradeProfileOperationsGenerateUpdateRunViaIdentity(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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.AutoUpgradeProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AutoUpgradeProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.AutoUpgradeProfileOperationsGenerateUpdateRun(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.AutoUpgradeProfileName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGenerateResponse + /// 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.ContainerServiceFleet.Models.IGenerateResponse + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet.cs new file mode 100644 index 00000000000..84b98f690b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet.cs @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Generates an generate run for a given auto upgrade profile. + /// + /// [OpenAPI] GenerateUpdateRun=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}/generateUpdateRun" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGenerateResponse))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Generates an generate run for a given auto upgrade profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}/generateUpdateRun", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private string _autoUpgradeProfileName; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string AutoUpgradeProfileName { get => this._autoUpgradeProfileName; set => this._autoUpgradeProfileName = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGenerateResponse + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet Clone() + { + var clone = new NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet(); + 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.AutoUpgradeProfileName = this.AutoUpgradeProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetAutoUpgradeProfileOperationUpdateRun_GenerateViaIdentityFleet() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfileOperationsGenerateUpdateRun' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/autoUpgradeProfiles/{(global::System.Uri.EscapeDataString(this.AutoUpgradeProfileName.ToString()))}"; + await this.Client.AutoUpgradeProfileOperationsGenerateUpdateRunViaIdentity(FleetInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.AutoUpgradeProfileOperationsGenerateUpdateRun(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, AutoUpgradeProfileName, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { AutoUpgradeProfileName=AutoUpgradeProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGenerateResponse + /// 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.ContainerServiceFleet.Models.IGenerateResponse + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded.cs new file mode 100644 index 00000000000..85ffb30b74c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded.cs @@ -0,0 +1,692 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a AutoUpgradeProfile + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetAutoUpgradeProfile_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The AutoUpgradeProfile resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } } + + /// Configures how auto-upgrade will be run. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Configures how auto-upgrade will be run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + public string Channel { get => _resourceBody.Channel ?? null; set => _resourceBody.Channel = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the + /// auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because + /// enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter Disabled { get => _resourceBody.Disabled ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.Disabled = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue + /// generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if + /// those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, + /// please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter LongTermSupport { get => _resourceBody.LongTermSupport ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.LongTermSupport = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// The node image upgrade type. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The node image upgrade type.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + public string NodeImageSelectionType { get => _resourceBody.NodeImageSelectionType ?? null; set => _resourceBody.NodeImageSelectionType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, \"1.30\". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string TargetKubernetesVersion { get => _resourceBody.TargetKubernetesVersion ?? null; set => _resourceBody.TargetKubernetesVersion = value; } + + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded Clone() + { + var clone = new NewAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetAutoUpgradeProfile_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..5e29f7d8d17 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath.cs @@ -0,0 +1,622 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a AutoUpgradeProfile + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath Clone() + { + var clone = new NewAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString.cs new file mode 100644 index 00000000000..72c1017eaf8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString.cs @@ -0,0 +1,620 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a AutoUpgradeProfile + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString Clone() + { + var clone = new NewAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetAutoUpgradeProfile_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateExpanded.cs new file mode 100644 index 00000000000..ffc1cbc1819 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateExpanded.cs @@ -0,0 +1,644 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a FleetMember + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetMember_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetMember_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 member of the Fleet. It contains a reference to an existing Kubernetes cluster on Azure. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMember(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.ClientAPI; + + /// + /// The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM resource id of the cluster that joins the Fleet. Must be a valid Azure resource id. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}'.", + SerializedName = @"clusterResourceId", + PossibleTypes = new [] { typeof(string) })] + public string ClusterResourceId { get => _resourceBody.ClusterResourceId ?? null; set => _resourceBody.ClusterResourceId = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// The group this member belongs to for multi-cluster update management. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The group this member belongs to for multi-cluster update management.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + public string Group { get => _resourceBody.Group ?? null; set => _resourceBody.Group = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The labels for the fleet member. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The labels for the fleet member.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberPropertiesLabels Label { get => _resourceBody.Label ?? null /* object */; set => _resourceBody.Label = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleetMember_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetMember_CreateExpanded Clone() + { + var clone = new NewAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetMember_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersCreate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..ba6170bb9bd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateViaJsonFilePath.cs @@ -0,0 +1,619 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a FleetMember + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetMember_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetMember_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleetMember_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetMember_CreateViaJsonFilePath Clone() + { + var clone = new NewAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetMember_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersCreateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_CreateViaJsonString.cs new file mode 100644 index 00000000000..071cd7bc8a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetMember_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a FleetMember + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetMember_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetMember_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleetMember_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetMember_CreateViaJsonString Clone() + { + var clone = new NewAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetMember_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersCreateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateExpanded.cs new file mode 100644 index 00000000000..ead3831b609 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateExpanded.cs @@ -0,0 +1,689 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a UpdateRun + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetUpdateRun_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetUpdateRun_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 multi-stage process to perform update operations across members of a Fleet. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.", + SerializedName = @"customNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion[] NodeImageSelectionCustomNodeImageVersion { get => _resourceBody.NodeImageSelectionCustomNodeImageVersion?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.NodeImageSelectionCustomNodeImageVersion = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The node image upgrade type. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The node image upgrade type.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + public string NodeImageSelectionType { get => _resourceBody.NodeImageSelectionType ?? null; set => _resourceBody.NodeImageSelectionType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define + /// a strategy for the run:1. Define a new strategy in place: Set the "strategy" field.2. Use an existing strategy: Set the + /// "updateStrategyId" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: + /// Leave both "updateStrategyId" and "strategy" unset. (since 2023-08-15-preview)Setting both "updateStrategyId" and "strategy" + /// is invalid.UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and + /// store it in the "strategy" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy + /// changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the \"strategy\" field.2. Use an existing strategy: Set the \"updateStrategyId\" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both \"updateStrategyId\" and \"strategy\" unset. (since 2023-08-15-preview)Setting both \"updateStrategyId\" and \"strategy\" is invalid.UpdateRuns created by \"updateStrategyId\" snapshot the referenced UpdateStrategy at the time of creation and store it in the \"strategy\" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the \"strategy\" field before launching the UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the ""strategy"" field.2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview)Setting both ""updateStrategyId"" and ""strategy"" is invalid.UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Kubernetes version to upgrade the member clusters to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string UpgradeKubernetesVersion { get => _resourceBody.UpgradeKubernetesVersion ?? null; set => _resourceBody.UpgradeKubernetesVersion = value; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "ManagedClusterUpgradeType is the type of upgrade to be applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + public string UpgradeType { get => _resourceBody.UpgradeType ?? null; set => _resourceBody.UpgradeType = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleetUpdateRun_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetUpdateRun_CreateExpanded Clone() + { + var clone = new NewAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetUpdateRun_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..d1aaa5a0591 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a UpdateRun + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetUpdateRun_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetUpdateRun_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetUpdateRun_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetUpdateRun_CreateViaJsonFilePath Clone() + { + var clone = new NewAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetUpdateRun_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_CreateViaJsonString.cs new file mode 100644 index 00000000000..4b824f89595 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateRun_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a UpdateRun + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetUpdateRun_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetUpdateRun_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleetUpdateRun_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetUpdateRun_CreateViaJsonString Clone() + { + var clone = new NewAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetUpdateRun_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateExpanded.cs new file mode 100644 index 00000000000..6e4fdfca78a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateExpanded.cs @@ -0,0 +1,619 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a FleetUpdateStrategy + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetUpdateStrategy_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleetUpdateStrategy_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleetUpdateStrategy_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetUpdateStrategy_CreateExpanded Clone() + { + var clone = new NewAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetUpdateStrategy_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..a346f2fdf23 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a FleetUpdateStrategy + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath Clone() + { + var clone = new NewAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString.cs new file mode 100644 index 00000000000..5d9c05ee2de --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a FleetUpdateStrategy + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleetUpdateStrategy_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString Clone() + { + var clone = new NewAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleetUpdateStrategy_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateExpanded.cs new file mode 100644 index 00000000000..c7d496cfff9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateExpanded.cs @@ -0,0 +1,723 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a Fleet. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleet_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + public partial class NewAzContainerServiceFleet_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The Fleet resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet(); + + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + public string AgentProfileSubnetId { get => _resourceBody.AgentProfileSubnetId ?? null; set => _resourceBody.AgentProfileSubnetId = value; } + + /// The virtual machine size of the Fleet hub. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The virtual machine size of the Fleet hub.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The virtual machine size of the Fleet hub.", + SerializedName = @"vmSize", + PossibleTypes = new [] { typeof(string) })] + public string AgentProfileVMSize { get => _resourceBody.AgentProfileVMSize ?? null; set => _resourceBody.AgentProfileVMSize = value; } + + /// Whether to create the Fleet hub as a private cluster or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to create the Fleet hub as a private cluster or not.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to create the Fleet hub as a private cluster or not.", + SerializedName = @"enablePrivateCluster", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter ApiServerAccessProfileEnablePrivateCluster { get => _resourceBody.ApiServerAccessProfileEnablePrivateCluster ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.ApiServerAccessProfileEnablePrivateCluster = value; } + + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to enable apiserver vnet integration for the Fleet hub or not.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to enable apiserver vnet integration for the Fleet hub or not.", + SerializedName = @"enableVnetIntegration", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter ApiServerAccessProfileEnableVnetIntegration { get => _resourceBody.ApiServerAccessProfileEnableVnetIntegration ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.ApiServerAccessProfileEnableVnetIntegration = value; } + + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + public string ApiServerAccessProfileSubnetId { get => _resourceBody.ApiServerAccessProfileSubnetId ?? null; set => _resourceBody.ApiServerAccessProfileSubnetId = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// DNS prefix used to create the FQDN for the Fleet hub. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "DNS prefix used to create the FQDN for the Fleet hub.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"DNS prefix used to create the FQDN for the Fleet hub.", + SerializedName = @"dnsPrefix", + PossibleTypes = new [] { typeof(string) })] + public string HubProfileDnsPrefix { get => _resourceBody.HubProfileDnsPrefix ?? null; set => _resourceBody.HubProfileDnsPrefix = value; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags 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; } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleet_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleet_CreateExpanded Clone() + { + var clone = new NewAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleet_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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.FleetsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..ff3715741bf --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a Fleet. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleet_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleet_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleet_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleet_CreateViaJsonFilePath Clone() + { + var clone = new NewAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleet_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_CreateViaJsonString.cs new file mode 100644 index 00000000000..f1f18f3702f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/NewAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// create a Fleet. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzContainerServiceFleet_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"create a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class NewAzContainerServiceFleet_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzContainerServiceFleet_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.NewAzContainerServiceFleet_CreateViaJsonString Clone() + { + var clone = new NewAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 NewAzContainerServiceFleet_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete.cs new file mode 100644 index 00000000000..4086fe25fd4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete.cs @@ -0,0 +1,625 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a AutoUpgradeProfile + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetAutoUpgradeProfile_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete Clone() + { + var clone = new RemoveAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesDelete(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetAutoUpgradeProfile_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity.cs new file mode 100644 index 00000000000..ac260122975 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a AutoUpgradeProfile + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity Clone() + { + var clone = new RemoveAzContainerServiceFleetAutoUpgradeProfile_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; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.AutoUpgradeProfilesDeleteViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, 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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.AutoUpgradeProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AutoUpgradeProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.AutoUpgradeProfilesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.AutoUpgradeProfileName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet.cs new file mode 100644 index 00000000000..bc75bb4b3f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet.cs @@ -0,0 +1,607 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a AutoUpgradeProfile + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet Clone() + { + var clone = new RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/autoUpgradeProfiles/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.AutoUpgradeProfilesDeleteViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.AutoUpgradeProfilesDelete(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public RemoveAzContainerServiceFleetAutoUpgradeProfile_DeleteViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_Delete.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_Delete.cs new file mode 100644 index 00000000000..bd18f4fab64 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_Delete.cs @@ -0,0 +1,625 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a FleetMember + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetMember_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetMember_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleetMember_Delete + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetMember_Delete Clone() + { + var clone = new RemoveAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersDelete(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetMember_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_DeleteViaIdentity.cs new file mode 100644 index 00000000000..dfb1189500e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_DeleteViaIdentity.cs @@ -0,0 +1,591 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a FleetMember + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetMember_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetMember_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleetMember_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetMember_DeleteViaIdentity Clone() + { + var clone = new RemoveAzContainerServiceFleetMember_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; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetMembersDeleteViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetMemberName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetMemberName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetMembersDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.FleetMemberName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetMember_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet.cs new file mode 100644 index 00000000000..52ef7243005 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a FleetMember + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetMember_DeleteViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet Clone() + { + var clone = new RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/members/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.FleetMembersDeleteViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.FleetMembersDelete(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetMember_DeleteViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_Delete.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_Delete.cs new file mode 100644 index 00000000000..1e6cd9383c3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_Delete.cs @@ -0,0 +1,625 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a UpdateRun + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetUpdateRun_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetUpdateRun_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleetUpdateRun_Delete + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetUpdateRun_Delete Clone() + { + var clone = new RemoveAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsDelete(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetUpdateRun_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity.cs new file mode 100644 index 00000000000..0673c44bdb1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a UpdateRun + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetUpdateRun_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity Clone() + { + var clone = new RemoveAzContainerServiceFleetUpdateRun_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; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UpdateRunsDeleteViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UpdateRunsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet.cs new file mode 100644 index 00000000000..ab8ff0d24da --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet.cs @@ -0,0 +1,607 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a UpdateRun + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet Clone() + { + var clone = new RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.UpdateRunsDeleteViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.UpdateRunsDelete(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzContainerServiceFleetUpdateRun_DeleteViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_Delete.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_Delete.cs new file mode 100644 index 00000000000..17d8f61965f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_Delete.cs @@ -0,0 +1,624 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a FleetUpdateStrategy + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetUpdateStrategy_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetUpdateStrategy_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleetUpdateStrategy_Delete + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetUpdateStrategy_Delete Clone() + { + var clone = new RemoveAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesDelete(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleetUpdateStrategy_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity.cs new file mode 100644 index 00000000000..d61e95c864c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a FleetUpdateStrategy + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetUpdateStrategy_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity Clone() + { + var clone = new RemoveAzContainerServiceFleetUpdateStrategy_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; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetUpdateStrategiesDeleteViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateStrategyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateStrategyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetUpdateStrategiesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateStrategyName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet.cs new file mode 100644 index 00000000000..6b9a29d952e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a FleetUpdateStrategy + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet Clone() + { + var clone = new RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.UpdateStrategyName = this.UpdateStrategyName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateStrategies/{(global::System.Uri.EscapeDataString(this.UpdateStrategyName.ToString()))}"; + await this.Client.FleetUpdateStrategiesDeleteViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.FleetUpdateStrategiesDelete(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RemoveAzContainerServiceFleetUpdateStrategy_DeleteViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleet_Delete.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleet_Delete.cs new file mode 100644 index 00000000000..318820b34c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleet_Delete.cs @@ -0,0 +1,610 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a Fleet + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleet_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleet_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleet_Delete + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleet_Delete Clone() + { + var clone = new RemoveAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsDelete(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleet_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleet_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleet_DeleteViaIdentity.cs new file mode 100644 index 00000000000..ce10e4f72ff --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/RemoveAzContainerServiceFleet_DeleteViaIdentity.cs @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Delete a Fleet + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzContainerServiceFleet_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Delete a Fleet")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + public partial class RemoveAzContainerServiceFleet_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzContainerServiceFleet_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.RemoveAzContainerServiceFleet_DeleteViaIdentity Clone() + { + var clone = new RemoveAzContainerServiceFleet_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; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetsDeleteViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzContainerServiceFleet_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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 == InvocationInformation?.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 / application/json + if (true == InvocationInformation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded.cs new file mode 100644 index 00000000000..09aad18c799 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded.cs @@ -0,0 +1,692 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a AutoUpgradeProfile + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + public partial class SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The AutoUpgradeProfile resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } } + + /// Configures how auto-upgrade will be run. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Configures how auto-upgrade will be run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + public string Channel { get => _resourceBody.Channel ?? null; set => _resourceBody.Channel = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the + /// auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because + /// enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter Disabled { get => _resourceBody.Disabled ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.Disabled = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue + /// generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if + /// those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, + /// please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter LongTermSupport { get => _resourceBody.LongTermSupport ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.LongTermSupport = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// The node image upgrade type. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The node image upgrade type.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent")] + public string NodeImageSelectionType { get => _resourceBody.NodeImageSelectionType ?? null; set => _resourceBody.NodeImageSelectionType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, \"1.30\". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string TargetKubernetesVersion { get => _resourceBody.TargetKubernetesVersion ?? null; set => _resourceBody.TargetKubernetesVersion = value; } + + /// + /// The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters + /// which are members of the fleet. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded Clone() + { + var clone = new SetAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..e698a49150b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath.cs @@ -0,0 +1,622 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a AutoUpgradeProfile + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString.cs new file mode 100644 index 00000000000..d1b6cd93845 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString.cs @@ -0,0 +1,620 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a AutoUpgradeProfile + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString Clone() + { + var clone = new SetAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AutoUpgradeProfilesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public SetAzContainerServiceFleetAutoUpgradeProfile_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateExpanded.cs new file mode 100644 index 00000000000..b8faeaebd0b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateExpanded.cs @@ -0,0 +1,689 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a UpdateRun + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetUpdateRun_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + public partial class SetAzContainerServiceFleetUpdateRun_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 multi-stage process to perform update operations across members of a Fleet. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, + /// it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one + /// version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not + /// both). If the nodes belong to a family without a matching image version in this field, they are not upgraded. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.", + SerializedName = @"customNodeImageVersions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.INodeImageVersion[] NodeImageSelectionCustomNodeImageVersion { get => _resourceBody.NodeImageSelectionCustomNodeImageVersion?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.NodeImageSelectionCustomNodeImageVersion = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// The node image upgrade type. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The node image upgrade type.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The node image upgrade type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Latest", "Consistent", "Custom")] + public string NodeImageSelectionType { get => _resourceBody.NodeImageSelectionType ?? null; set => _resourceBody.NodeImageSelectionType = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define + /// a strategy for the run:1. Define a new strategy in place: Set the "strategy" field.2. Use an existing strategy: Set the + /// "updateStrategyId" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: + /// Leave both "updateStrategyId" and "strategy" unset. (since 2023-08-15-preview)Setting both "updateStrategyId" and "strategy" + /// is invalid.UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and + /// store it in the "strategy" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy + /// changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the \"strategy\" field.2. Use an existing strategy: Set the \"updateStrategyId\" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both \"updateStrategyId\" and \"strategy\" unset. (since 2023-08-15-preview)Setting both \"updateStrategyId\" and \"strategy\" is invalid.UpdateRuns created by \"updateStrategyId\" snapshot the referenced UpdateStrategy at the time of creation and store it in the \"strategy\" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the \"strategy\" field before launching the UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the ""strategy"" field.2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview)Setting both ""updateStrategyId"" and ""strategy"" is invalid.UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Kubernetes version to upgrade the member clusters to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string UpgradeKubernetesVersion { get => _resourceBody.UpgradeKubernetesVersion ?? null; set => _resourceBody.UpgradeKubernetesVersion = value; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "ManagedClusterUpgradeType is the type of upgrade to be applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + public string UpgradeType { get => _resourceBody.UpgradeType ?? null; set => _resourceBody.UpgradeType = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzContainerServiceFleetUpdateRun_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetUpdateRun_UpdateExpanded Clone() + { + var clone = new SetAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleetUpdateRun_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..4b075d90ab3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a UpdateRun + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleetUpdateRun_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString.cs new file mode 100644 index 00000000000..f34502a50ef --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a UpdateRun + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetUpdateRun_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString Clone() + { + var clone = new SetAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleetUpdateRun_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded.cs new file mode 100644 index 00000000000..c8b75b50b6c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded.cs @@ -0,0 +1,619 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetUpdateStrategy + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetUpdateStrategy_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + public partial class SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded Clone() + { + var clone = new SetAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleetUpdateStrategy_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..b57d0fbe8bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetUpdateStrategy + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString.cs new file mode 100644 index 00000000000..7259bb561cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetUpdateStrategy + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleetUpdateStrategy_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString Clone() + { + var clone = new SetAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetUpdateStrategiesCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleetUpdateStrategy_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateExpanded.cs new file mode 100644 index 00000000000..c00d775bc07 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateExpanded.cs @@ -0,0 +1,723 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Fleet. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleet_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + public partial class SetAzContainerServiceFleet_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The Fleet resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet(); + + /// + /// The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be + /// generated and used. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ID of the subnet which the Fleet hub node will join on startup. If this is not specified, a vnet and subnet will be generated and used.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + public string AgentProfileSubnetId { get => _resourceBody.AgentProfileSubnetId ?? null; set => _resourceBody.AgentProfileSubnetId = value; } + + /// The virtual machine size of the Fleet hub. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The virtual machine size of the Fleet hub.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The virtual machine size of the Fleet hub.", + SerializedName = @"vmSize", + PossibleTypes = new [] { typeof(string) })] + public string AgentProfileVMSize { get => _resourceBody.AgentProfileVMSize ?? null; set => _resourceBody.AgentProfileVMSize = value; } + + /// Whether to create the Fleet hub as a private cluster or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to create the Fleet hub as a private cluster or not.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to create the Fleet hub as a private cluster or not.", + SerializedName = @"enablePrivateCluster", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter ApiServerAccessProfileEnablePrivateCluster { get => _resourceBody.ApiServerAccessProfileEnablePrivateCluster ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.ApiServerAccessProfileEnablePrivateCluster = value; } + + /// Whether to enable apiserver vnet integration for the Fleet hub or not. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to enable apiserver vnet integration for the Fleet hub or not.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to enable apiserver vnet integration for the Fleet hub or not.", + SerializedName = @"enableVnetIntegration", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter ApiServerAccessProfileEnableVnetIntegration { get => _resourceBody.ApiServerAccessProfileEnableVnetIntegration ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.ApiServerAccessProfileEnableVnetIntegration = value; } + + /// + /// The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The subnet to be used when apiserver vnet integration is enabled. It is required when creating a new Fleet with BYO vnet.", + SerializedName = @"subnetId", + PossibleTypes = new [] { typeof(string) })] + public string ApiServerAccessProfileSubnetId { get => _resourceBody.ApiServerAccessProfileSubnetId ?? null; set => _resourceBody.ApiServerAccessProfileSubnetId = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// DNS prefix used to create the FQDN for the Fleet hub. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "DNS prefix used to create the FQDN for the Fleet hub.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"DNS prefix used to create the FQDN for the Fleet hub.", + SerializedName = @"dnsPrefix", + PossibleTypes = new [] { typeof(string) })] + public string HubProfileDnsPrefix { get => _resourceBody.HubProfileDnsPrefix ?? null; set => _resourceBody.HubProfileDnsPrefix = value; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags 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; } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzContainerServiceFleet_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleet_UpdateExpanded Clone() + { + var clone = new SetAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.FleetsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleet_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..e4537f2852d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Fleet. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleet_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleet_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzContainerServiceFleet_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleet_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleet_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_UpdateViaJsonString.cs new file mode 100644 index 00000000000..1c737f6d522 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SetAzContainerServiceFleet_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Fleet. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzContainerServiceFleet_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SetAzContainerServiceFleet_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzContainerServiceFleet_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SetAzContainerServiceFleet_UpdateViaJsonString Clone() + { + var clone = new SetAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzContainerServiceFleet_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_Skip.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_Skip.cs new file mode 100644 index 00000000000..0666b4c6879 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_Skip.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_Skip", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + public partial class SkipAzContainerServiceFleetUpdateRun_Skip : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties _body; + + /// The properties of a skip operation containing multiple skip requests. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The properties of a skip operation containing multiple skip requests.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The properties of a skip operation containing multiple skip requests.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_Skip + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_Skip Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_Skip(); + 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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.Body = this.Body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsSkip(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, Body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_Skip() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipExpanded.cs new file mode 100644 index 00000000000..f92032bb4c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipExpanded.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 properties of a skip operation containing multiple skip requests. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties _body = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SkipProperties(); + + /// + /// 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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// The targets to skip. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The targets to skip.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The targets to skip.", + SerializedName = @"targets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget[] Target { get => _body.Target?.ToArray() ?? null /* fixedArrayOf */; set => _body.Target = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipExpanded Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipExpanded(); + 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._body = this._body; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsSkip(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity.cs new file mode 100644 index 00000000000..530fe3661a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity.cs @@ -0,0 +1,570 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties _body; + + /// The properties of a skip operation containing multiple skip requests. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The properties of a skip operation containing multiple skip requests.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The properties of a skip operation containing multiple skip requests.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity(); + 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.IfMatch = this.IfMatch; + clone.Body = this.Body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UpdateRunsSkipViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, Body, 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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UpdateRunsSkip(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded.cs new file mode 100644 index 00000000000..44dca2b9e42 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded.cs @@ -0,0 +1,573 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 properties of a skip operation containing multiple skip requests. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties _body = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SkipProperties(); + + /// + /// 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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The targets to skip. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The targets to skip.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The targets to skip.", + SerializedName = @"targets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget[] Target { get => _body.Target?.ToArray() ?? null /* fixedArrayOf */; set => _body.Target = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded(); + 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._body = this._body; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UpdateRunsSkipViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _body, 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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UpdateRunsSkip(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet.cs new file mode 100644 index 00000000000..04125270f98 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet.cs @@ -0,0 +1,585 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties _body; + + /// The properties of a skip operation containing multiple skip requests. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The properties of a skip operation containing multiple skip requests.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The properties of a skip operation containing multiple skip requests.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + clone.Body = this.Body; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.UpdateRunsSkipViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, Body, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.UpdateRunsSkip(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, Body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded.cs new file mode 100644 index 00000000000..8640c3ffd58 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded.cs @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 properties of a skip operation containing multiple skip requests. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipProperties _body = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.SkipProperties(); + + /// + /// 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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The targets to skip. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The targets to skip.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The targets to skip.", + SerializedName = @"targets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ISkipTarget[] Target { get => _body.Target?.ToArray() ?? null /* fixedArrayOf */; set => _body.Target = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded(); + 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._body = this._body; + clone.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.UpdateRunsSkipViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _body, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.UpdateRunsSkip(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _body, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipViaIdentityFleetExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath.cs new file mode 100644 index 00000000000..ba01de6bb91 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// 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 Skip operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Skip operation")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Skip 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath(); + 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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsSkipViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString.cs new file mode 100644 index 00000000000..a5660fa2386 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// + /// Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run. + /// + /// + /// [OpenAPI] Skip=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Skip, @"AzContainerServiceFleetUpdateRun_SkipViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Skips one or a combination of member/group/stage/afterStageWait(s) of an skip run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/skip", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// 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 Skip operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Skip operation")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Skip 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString Clone() + { + var clone = new SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString(); + 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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsSkip' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsSkipViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SkipAzContainerServiceFleetUpdateRun_SkipViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_Start.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_Start.cs new file mode 100644 index 00000000000..0a04192faad --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_Start.cs @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Starts an UpdateRun. + /// + /// [OpenAPI] Start=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/start" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Start, @"AzContainerServiceFleetUpdateRun_Start", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Starts an UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/start", ApiVersion = "2025-04-01-preview")] + public partial class StartAzContainerServiceFleetUpdateRun_Start : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StartAzContainerServiceFleetUpdateRun_Start + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.StartAzContainerServiceFleetUpdateRun_Start Clone() + { + var clone = new StartAzContainerServiceFleetUpdateRun_Start(); + 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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsStart' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsStart(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StartAzContainerServiceFleetUpdateRun_Start() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_StartViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_StartViaIdentity.cs new file mode 100644 index 00000000000..b30535e2b32 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_StartViaIdentity.cs @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Starts an UpdateRun. + /// + /// [OpenAPI] Start=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/start" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Start, @"AzContainerServiceFleetUpdateRun_StartViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Starts an UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/start", ApiVersion = "2025-04-01-preview")] + public partial class StartAzContainerServiceFleetUpdateRun_StartViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StartAzContainerServiceFleetUpdateRun_StartViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.StartAzContainerServiceFleetUpdateRun_StartViaIdentity Clone() + { + var clone = new StartAzContainerServiceFleetUpdateRun_StartViaIdentity(); + 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.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsStart' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UpdateRunsStartViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, 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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UpdateRunsStart(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StartAzContainerServiceFleetUpdateRun_StartViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet.cs new file mode 100644 index 00000000000..d73d0efb6d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Starts an UpdateRun. + /// + /// [OpenAPI] Start=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/start" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Start, @"AzContainerServiceFleetUpdateRun_StartViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Starts an UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/start", ApiVersion = "2025-04-01-preview")] + public partial class StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet Clone() + { + var clone = new StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsStart' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.UpdateRunsStartViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.UpdateRunsStart(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StartAzContainerServiceFleetUpdateRun_StartViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_Stop.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_Stop.cs new file mode 100644 index 00000000000..82834863386 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_Stop.cs @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Stops an UpdateRun. + /// + /// [OpenAPI] Stop=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/stop" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Stop, @"AzContainerServiceFleetUpdateRun_Stop", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Stops an UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/stop", ApiVersion = "2025-04-01-preview")] + public partial class StopAzContainerServiceFleetUpdateRun_Stop : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StopAzContainerServiceFleetUpdateRun_Stop + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.StopAzContainerServiceFleetUpdateRun_Stop Clone() + { + var clone = new StopAzContainerServiceFleetUpdateRun_Stop(); + 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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsStop' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UpdateRunsStop(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StopAzContainerServiceFleetUpdateRun_Stop() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_StopViaIdentity.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_StopViaIdentity.cs new file mode 100644 index 00000000000..1758d1d3849 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_StopViaIdentity.cs @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Stops an UpdateRun. + /// + /// [OpenAPI] Stop=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/stop" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Stop, @"AzContainerServiceFleetUpdateRun_StopViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Stops an UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/stop", ApiVersion = "2025-04-01-preview")] + public partial class StopAzContainerServiceFleetUpdateRun_StopViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of StopAzContainerServiceFleetUpdateRun_StopViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.StopAzContainerServiceFleetUpdateRun_StopViaIdentity Clone() + { + var clone = new StopAzContainerServiceFleetUpdateRun_StopViaIdentity(); + 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.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsStop' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UpdateRunsStopViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, 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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UpdateRunsStop(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StopAzContainerServiceFleetUpdateRun_StopViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet.cs new file mode 100644 index 00000000000..0fd4e503391 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet.cs @@ -0,0 +1,568 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// Stops an UpdateRun. + /// + /// [OpenAPI] Stop=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/stop" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Stop, @"AzContainerServiceFleetUpdateRun_StopViaIdentityFleet", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"Stops an UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}/stop", ApiVersion = "2025-04-01-preview")] + public partial class StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet Clone() + { + var clone = new StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsStop' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.UpdateRunsStopViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.UpdateRunsStop(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public StopAzContainerServiceFleetUpdateRun_StopViaIdentityFleet() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded.cs new file mode 100644 index 00000000000..582d7f6f26f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded.cs @@ -0,0 +1,689 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a AutoUpgradeProfile + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The AutoUpgradeProfile resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } } + + /// Configures how auto-upgrade will be run. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Configures how auto-upgrade will be run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + public string Channel { get => _resourceBody.Channel ?? null; set => _resourceBody.Channel = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the + /// auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because + /// enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter Disabled { get => _resourceBody.Disabled ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.Disabled = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue + /// generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if + /// those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, + /// please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter LongTermSupport { get => _resourceBody.LongTermSupport ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.LongTermSupport = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, \"1.30\". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string TargetKubernetesVersion { get => _resourceBody.TargetKubernetesVersion ?? null; set => _resourceBody.TargetKubernetesVersion = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetAutoUpgradeProfile_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.AutoUpgradeProfilesGetWithResult(SubscriptionId, ResourceGroupName, FleetName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.AutoUpgradeProfilesCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Channel"))) + { + this.Channel = (string)(this.MyInvocation?.BoundParameters["Channel"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Disabled"))) + { + this.Disabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["Disabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("TargetKubernetesVersion"))) + { + this.TargetKubernetesVersion = (string)(this.MyInvocation?.BoundParameters["TargetKubernetesVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("LongTermSupport"))) + { + this.LongTermSupport = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["LongTermSupport"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..06cbe83b4e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded.cs @@ -0,0 +1,657 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a AutoUpgradeProfile + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The AutoUpgradeProfile resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } } + + /// Configures how auto-upgrade will be run. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Configures how auto-upgrade will be run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + public string Channel { get => _resourceBody.Channel ?? null; set => _resourceBody.Channel = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the + /// auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because + /// enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter Disabled { get => _resourceBody.Disabled ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.Disabled = 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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; } } + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue + /// generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if + /// those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, + /// please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter LongTermSupport { get => _resourceBody.LongTermSupport ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.LongTermSupport = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, \"1.30\". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string TargetKubernetesVersion { get => _resourceBody.TargetKubernetesVersion ?? null; set => _resourceBody.TargetKubernetesVersion = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetAutoUpgradeProfile_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; + clone.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.AutoUpgradeProfilesGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.AutoUpgradeProfilesCreateOrUpdateViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.AutoUpgradeProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AutoUpgradeProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.AutoUpgradeProfilesGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.AutoUpgradeProfileName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.AutoUpgradeProfilesCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.AutoUpgradeProfileName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Channel"))) + { + this.Channel = (string)(this.MyInvocation?.BoundParameters["Channel"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Disabled"))) + { + this.Disabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["Disabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("TargetKubernetesVersion"))) + { + this.TargetKubernetesVersion = (string)(this.MyInvocation?.BoundParameters["TargetKubernetesVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("LongTermSupport"))) + { + this.LongTermSupport = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["LongTermSupport"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded.cs new file mode 100644 index 00000000000..faa0574a3ff --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded.cs @@ -0,0 +1,670 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a AutoUpgradeProfile + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/autoUpgradeProfiles/{autoUpgradeProfileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a AutoUpgradeProfile")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The AutoUpgradeProfile resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IAutoUpgradeProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.AutoUpgradeProfile(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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; } } + + /// Configures how auto-upgrade will be run. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Configures how auto-upgrade will be run.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Configures how auto-upgrade will be run.", + SerializedName = @"channel", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Stable", "Rapid", "NodeImage", "TargetKubernetesVersion")] + public string Channel { get => _resourceBody.Channel ?? null; set => _resourceBody.Channel = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// + /// If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the + /// auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because + /// enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule.If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters.This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile.By default, this is set to False.", + SerializedName = @"disabled", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter Disabled { get => _resourceBody.Disabled ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.Disabled = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue + /// generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if + /// those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, + /// please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" If upgrade channel is not TargetKubernetesVersion, this field must be False. If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). By default, this is set to False. For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support", + SerializedName = @"longTermSupport", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter LongTermSupport { get => _resourceBody.LongTermSupport ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.LongTermSupport = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the AutoUpgradeProfile resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AutoUpgradeProfile resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AutoUpgradeProfile resource.", + SerializedName = @"autoUpgradeProfileName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AutoUpgradeProfileName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, + /// "1.30". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + /// If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = " This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, \"1.30\". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, ""1.30"". By default, this is empty. If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. If upgrade channel is Rapid, Stable or NodeImage, this field must be empty.", + SerializedName = @"targetKubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string TargetKubernetesVersion { get => _resourceBody.TargetKubernetesVersion ?? null; set => _resourceBody.TargetKubernetesVersion = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded(); + 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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AutoUpgradeProfilesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/autoUpgradeProfiles/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.AutoUpgradeProfilesGetViaIdentityWithResult(FleetInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.AutoUpgradeProfilesCreateOrUpdateViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + _resourceBody = await this.Client.AutoUpgradeProfilesGetWithResult(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.AutoUpgradeProfilesCreateOrUpdate(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetAutoUpgradeProfile_UpdateViaIdentityFleetExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Channel"))) + { + this.Channel = (string)(this.MyInvocation?.BoundParameters["Channel"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Disabled"))) + { + this.Disabled = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["Disabled"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("TargetKubernetesVersion"))) + { + this.TargetKubernetesVersion = (string)(this.MyInvocation?.BoundParameters["TargetKubernetesVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("LongTermSupport"))) + { + this.LongTermSupport = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["LongTermSupport"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IAutoUpgradeProfile + /// 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.ContainerServiceFleet.Models.IAutoUpgradeProfile + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateExpanded.cs new file mode 100644 index 00000000000..b95f32f4fdc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateExpanded.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Gate + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetGate_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + public partial class UpdateAzContainerServiceFleetGate_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// Patch a Gate resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatch(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Gate resource, a GUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Gate resource, a GUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("GateName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The state of the Gate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The state of the Gate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + public string State { get => _propertiesBody.State ?? null; set => _propertiesBody.State = 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleetGate_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetGate_UpdateExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetGate_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GatesUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GatesUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetGate_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..920060dc3e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Gate + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetGate_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + public partial class UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// Patch a Gate resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatch(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The state of the Gate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The state of the Gate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + public string State { get => _propertiesBody.State ?? null; set => _propertiesBody.State = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetGate_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; + clone.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GatesUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.GatesUpdateViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.GateName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.GateName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.GatesUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.GateName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetGate_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded.cs new file mode 100644 index 00000000000..ec15479d128 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded.cs @@ -0,0 +1,600 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Gate + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + public partial class UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// Patch a Gate resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGatePatch _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.GatePatch(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Gate resource, a GUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Gate resource, a GUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("GateName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The state of the Gate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The state of the Gate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The state of the Gate.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Pending", "Skipped", "Completed")] + public string State { get => _propertiesBody.State ?? null; set => _propertiesBody.State = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded(); + 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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GatesUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/gates/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.GatesUpdateViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.GatesUpdate(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzContainerServiceFleetGate_UpdateViaIdentityFleetExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..4109ab5d7b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath.cs @@ -0,0 +1,619 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Gate + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetGate_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Gate resource, a GUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Gate resource, a GUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("GateName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzContainerServiceFleetGate_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GatesUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GatesUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetGate_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaJsonString.cs new file mode 100644 index 00000000000..54696fb4267 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetGate_UpdateViaJsonString.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Gate + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetGate_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IGate))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Gate")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/gates/{gateName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class UpdateAzContainerServiceFleetGate_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Gate resource, a GUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Gate resource, a GUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Gate resource, a GUID.", + SerializedName = @"gateName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("GateName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleetGate_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetGate_UpdateViaJsonString Clone() + { + var clone = new UpdateAzContainerServiceFleetGate_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'GatesUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.GatesUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetGate_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IGate + /// 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.ContainerServiceFleet.Models.IGate + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateExpanded.cs new file mode 100644 index 00000000000..5bcbe309a86 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateExpanded.cs @@ -0,0 +1,614 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetMember + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetMember_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class UpdateAzContainerServiceFleetMember_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The type used for update operations of the FleetMember. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdate(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// The group this member belongs to for multi-cluster update management. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The group this member belongs to for multi-cluster update management.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + public string Group { get => _propertiesBody.Group ?? null; set => _propertiesBody.Group = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The labels for the fleet member. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The labels for the fleet member.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get => _propertiesBody.Label ?? null /* object */; set => _propertiesBody.Label = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleetMember_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetMember_UpdateExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetMember_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..350d6eea657 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded.cs @@ -0,0 +1,583 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetMember + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetMember_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The type used for update operations of the FleetMember. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdate(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// The group this member belongs to for multi-cluster update management. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The group this member belongs to for multi-cluster update management.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + public string Group { get => _propertiesBody.Group ?? null; set => _propertiesBody.Group = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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 labels for the fleet member. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The labels for the fleet member.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get => _propertiesBody.Label ?? null /* object */; set => _propertiesBody.Label = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetMember_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; + clone.IfMatch = this.IfMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FleetMembersUpdateViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.FleetMemberName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetMemberName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FleetMembersUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.FleetMemberName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzContainerServiceFleetMember_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded.cs new file mode 100644 index 00000000000..231cfcc03cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded.cs @@ -0,0 +1,596 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetMember + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + public partial class UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The type used for update operations of the FleetMember. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdate _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetMemberUpdate(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// The group this member belongs to for multi-cluster update management. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The group this member belongs to for multi-cluster update management.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The group this member belongs to for multi-cluster update management.", + SerializedName = @"group", + PossibleTypes = new [] { typeof(string) })] + public string Group { get => _propertiesBody.Group ?? null; set => _propertiesBody.Group = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The labels for the fleet member. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The labels for the fleet member.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The labels for the fleet member.", + SerializedName = @"labels", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMemberUpdatePropertiesLabels Label { get => _propertiesBody.Label ?? null /* object */; set => _propertiesBody.Label = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded(); + 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.IfMatch = this.IfMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/members/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + await this.Client.FleetMembersUpdateViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + await this.Client.FleetMembersUpdate(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzContainerServiceFleetMember_UpdateViaIdentityFleetExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..5a2a6a4ade3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetMember + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetMember_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class UpdateAzContainerServiceFleetMember_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + public global::System.String _jsonString; + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetMember_UpdateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetMember_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetMember_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_UpdateViaJsonString.cs new file mode 100644 index 00000000000..79f03d83428 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetMember_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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetMember + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetMember_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetMember))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetMember")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/members/{fleetMemberName}", ApiVersion = "2025-04-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.NotSuggestDefaultParameterSet] + public partial class UpdateAzContainerServiceFleetMember_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet member resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet member resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet member resource.", + SerializedName = @"fleetMemberName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetMemberName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleetMember_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetMember_UpdateViaJsonString Clone() + { + var clone = new UpdateAzContainerServiceFleetMember_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.IfMatch = this.IfMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetMembersUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FleetMembersUpdateViaJsonString(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetMember_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetMember + /// 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.ContainerServiceFleet.Models.IFleetMember + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded.cs new file mode 100644 index 00000000000..fb15283b01c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded.cs @@ -0,0 +1,682 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a UpdateRun + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetUpdateRun_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 multi-stage process to perform update operations across members of a Fleet. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define + /// a strategy for the run:1. Define a new strategy in place: Set the "strategy" field.2. Use an existing strategy: Set the + /// "updateStrategyId" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: + /// Leave both "updateStrategyId" and "strategy" unset. (since 2023-08-15-preview)Setting both "updateStrategyId" and "strategy" + /// is invalid.UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and + /// store it in the "strategy" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy + /// changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the \"strategy\" field.2. Use an existing strategy: Set the \"updateStrategyId\" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both \"updateStrategyId\" and \"strategy\" unset. (since 2023-08-15-preview)Setting both \"updateStrategyId\" and \"strategy\" is invalid.UpdateRuns created by \"updateStrategyId\" snapshot the referenced UpdateStrategy at the time of creation and store it in the \"strategy\" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the \"strategy\" field before launching the UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the ""strategy"" field.2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview)Setting both ""updateStrategyId"" and ""strategy"" is invalid.UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Kubernetes version to upgrade the member clusters to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string UpgradeKubernetesVersion { get => _resourceBody.UpgradeKubernetesVersion ?? null; set => _resourceBody.UpgradeKubernetesVersion = value; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "ManagedClusterUpgradeType is the type of upgrade to be applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + public string UpgradeType { get => _resourceBody.UpgradeType ?? null; set => _resourceBody.UpgradeType = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetUpdateRun_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.UpdateRunsGetWithResult(SubscriptionId, ResourceGroupName, FleetName, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.UpdateRunsCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetUpdateRun_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpdateStrategyId"))) + { + this.UpdateStrategyId = (string)(this.MyInvocation?.BoundParameters["UpdateStrategyId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StrategyStage"))) + { + this.StrategyStage = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[])(this.MyInvocation?.BoundParameters["StrategyStage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpgradeKubernetesVersion"))) + { + this.UpgradeKubernetesVersion = (string)(this.MyInvocation?.BoundParameters["UpgradeKubernetesVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpgradeType"))) + { + this.UpgradeType = (string)(this.MyInvocation?.BoundParameters["UpgradeType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..a2c04eb8ed5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded.cs @@ -0,0 +1,653 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a UpdateRun + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 multi-stage process to perform update operations across members of a Fleet. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define + /// a strategy for the run:1. Define a new strategy in place: Set the "strategy" field.2. Use an existing strategy: Set the + /// "updateStrategyId" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: + /// Leave both "updateStrategyId" and "strategy" unset. (since 2023-08-15-preview)Setting both "updateStrategyId" and "strategy" + /// is invalid.UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and + /// store it in the "strategy" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy + /// changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the \"strategy\" field.2. Use an existing strategy: Set the \"updateStrategyId\" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both \"updateStrategyId\" and \"strategy\" unset. (since 2023-08-15-preview)Setting both \"updateStrategyId\" and \"strategy\" is invalid.UpdateRuns created by \"updateStrategyId\" snapshot the referenced UpdateStrategy at the time of creation and store it in the \"strategy\" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the \"strategy\" field before launching the UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the ""strategy"" field.2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview)Setting both ""updateStrategyId"" and ""strategy"" is invalid.UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Kubernetes version to upgrade the member clusters to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string UpgradeKubernetesVersion { get => _resourceBody.UpgradeKubernetesVersion ?? null; set => _resourceBody.UpgradeKubernetesVersion = value; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "ManagedClusterUpgradeType is the type of upgrade to be applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + public string UpgradeType { get => _resourceBody.UpgradeType ?? null; set => _resourceBody.UpgradeType = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetUpdateRun_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; + clone.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.UpdateRunsGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.UpdateRunsCreateOrUpdateViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateRunName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateRunName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.UpdateRunsGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.UpdateRunsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateRunName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpdateStrategyId"))) + { + this.UpdateStrategyId = (string)(this.MyInvocation?.BoundParameters["UpdateStrategyId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StrategyStage"))) + { + this.StrategyStage = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[])(this.MyInvocation?.BoundParameters["StrategyStage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpgradeKubernetesVersion"))) + { + this.UpgradeKubernetesVersion = (string)(this.MyInvocation?.BoundParameters["UpgradeKubernetesVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpgradeType"))) + { + this.UpgradeType = (string)(this.MyInvocation?.BoundParameters["UpgradeType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded.cs new file mode 100644 index 00000000000..84ddd7187cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded.cs @@ -0,0 +1,666 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a UpdateRun + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a UpdateRun")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 multi-stage process to perform update operations across members of a Fleet. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateRun _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.UpdateRun(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the UpdateRun resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateRun resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateRun resource.", + SerializedName = @"updateRunName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("UpdateRunName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define + /// a strategy for the run:1. Define a new strategy in place: Set the "strategy" field.2. Use an existing strategy: Set the + /// "updateStrategyId" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: + /// Leave both "updateStrategyId" and "strategy" unset. (since 2023-08-15-preview)Setting both "updateStrategyId" and "strategy" + /// is invalid.UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and + /// store it in the "strategy" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy + /// changes can be made directly on the "strategy" field before launching the UpdateRun. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the \"strategy\" field.2. Use an existing strategy: Set the \"updateStrategyId\" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both \"updateStrategyId\" and \"strategy\" unset. (since 2023-08-15-preview)Setting both \"updateStrategyId\" and \"strategy\" is invalid.UpdateRuns created by \"updateStrategyId\" snapshot the referenced UpdateStrategy at the time of creation and store it in the \"strategy\" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the \"strategy\" field before launching the UpdateRun.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource id of the FleetUpdateStrategy resource to reference.When creating a new run, there are three ways to define a strategy for the run:1. Define a new strategy in place: Set the ""strategy"" field.2. Use an existing strategy: Set the ""updateStrategyId"" field. (since 2023-08-15-preview)3. Use the default strategy to update all the members one by one: Leave both ""updateStrategyId"" and ""strategy"" unset. (since 2023-08-15-preview)Setting both ""updateStrategyId"" and ""strategy"" is invalid.UpdateRuns created by ""updateStrategyId"" snapshot the referenced UpdateStrategy at the time of creation and store it in the ""strategy"" field. Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate.UpdateRunStrategy changes can be made directly on the ""strategy"" field before launching the UpdateRun.", + SerializedName = @"updateStrategyId", + PossibleTypes = new [] { typeof(string) })] + public string UpdateStrategyId { get => _resourceBody.UpdateStrategyId ?? null; set => _resourceBody.UpdateStrategyId = value; } + + /// The Kubernetes version to upgrade the member clusters to. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The Kubernetes version to upgrade the member clusters to.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes version to upgrade the member clusters to.", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + public string UpgradeKubernetesVersion { get => _resourceBody.UpgradeKubernetesVersion ?? null; set => _resourceBody.UpgradeKubernetesVersion = value; } + + /// ManagedClusterUpgradeType is the type of upgrade to be applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "ManagedClusterUpgradeType is the type of upgrade to be applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"ManagedClusterUpgradeType is the type of upgrade to be applied.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.PSArgumentCompleterAttribute("Full", "NodeImageOnly", "ControlPlaneOnly")] + public string UpgradeType { get => _resourceBody.UpgradeType ?? null; set => _resourceBody.UpgradeType = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded(); + 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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UpdateRunsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateRuns/{(global::System.Uri.EscapeDataString(this.Name.ToString()))}"; + _resourceBody = await this.Client.UpdateRunsGetViaIdentityWithResult(FleetInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.UpdateRunsCreateOrUpdateViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + _resourceBody = await this.Client.UpdateRunsGetWithResult(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this, Pipeline); + this.Update_resourceBody(); + await this.Client.UpdateRunsCreateOrUpdate(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public UpdateAzContainerServiceFleetUpdateRun_UpdateViaIdentityFleetExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpdateStrategyId"))) + { + this.UpdateStrategyId = (string)(this.MyInvocation?.BoundParameters["UpdateStrategyId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StrategyStage"))) + { + this.StrategyStage = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[])(this.MyInvocation?.BoundParameters["StrategyStage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpgradeKubernetesVersion"))) + { + this.UpgradeKubernetesVersion = (string)(this.MyInvocation?.BoundParameters["UpgradeKubernetesVersion"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UpgradeType"))) + { + this.UpgradeType = (string)(this.MyInvocation?.BoundParameters["UpgradeType"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IUpdateRun + /// 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.ContainerServiceFleet.Models.IUpdateRun + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded.cs new file mode 100644 index 00000000000..1c4c7555e3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded.cs @@ -0,0 +1,631 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetUpdateStrategy + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetUpdateStrategy_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private string _fleetName; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string FleetName { get => this._fleetName; set => this._fleetName = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetUpdateStrategy_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.FleetName = this.FleetName; + clone.UpdateStrategyName = this.UpdateStrategyName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.FleetUpdateStrategiesGetWithResult(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FleetUpdateStrategiesCreateOrUpdate(SubscriptionId, ResourceGroupName, FleetName, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,FleetName=FleetName,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetUpdateStrategy_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StrategyStage"))) + { + this.StrategyStage = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[])(this.MyInvocation?.BoundParameters["StrategyStage"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..dd3667eb942 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded.cs @@ -0,0 +1,601 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetUpdateStrategy + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetUpdateStrategy_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; + clone.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.FleetUpdateStrategiesGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FleetUpdateStrategiesCreateOrUpdateViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.UpdateStrategyName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.UpdateStrategyName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.FleetUpdateStrategiesGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateStrategyName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FleetUpdateStrategiesCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, InputObject.UpdateStrategyName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StrategyStage"))) + { + this.StrategyStage = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[])(this.MyInvocation?.BoundParameters["StrategyStage"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded.cs new file mode 100644 index 00000000000..df29c45607f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded.cs @@ -0,0 +1,613 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a FleetUpdateStrategy + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateStrategies/{updateStrategyName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a FleetUpdateStrategy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// + /// Defines a multi-stage process to perform update operations across members of a Fleet. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleetUpdateStrategy _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.FleetUpdateStrategy(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _fleetInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity FleetInputObject { get => this._fleetInputObject; set => this._fleetInputObject = value; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The list of stages that compose this update run. Min size: 1. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of stages that compose this update run. Min size: 1.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of stages that compose this update run. Min size: 1.", + SerializedName = @"stages", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[] StrategyStage { get => _resourceBody.StrategyStage?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.StrategyStage = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// Backing field for property. + private string _updateStrategyName; + + /// The name of the UpdateStrategy resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the UpdateStrategy resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the UpdateStrategy resource.", + SerializedName = @"updateStrategyName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string UpdateStrategyName { get => this._updateStrategyName; set => this._updateStrategyName = 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded(); + 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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.UpdateStrategyName = this.UpdateStrategyName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetUpdateStrategiesCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (FleetInputObject?.Id != null) + { + this.FleetInputObject.Id += $"/updateStrategies/{(global::System.Uri.EscapeDataString(this.UpdateStrategyName.ToString()))}"; + _resourceBody = await this.Client.FleetUpdateStrategiesGetViaIdentityWithResult(FleetInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FleetUpdateStrategiesCreateOrUpdateViaIdentity(FleetInputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == FleetInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + if (null == FleetInputObject.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("FleetInputObject has null value for FleetInputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, FleetInputObject) ); + } + _resourceBody = await this.Client.FleetUpdateStrategiesGetWithResult(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, UpdateStrategyName, this, Pipeline); + this.Update_resourceBody(); + await this.Client.FleetUpdateStrategiesCreateOrUpdate(FleetInputObject.SubscriptionId ?? null, FleetInputObject.ResourceGroupName ?? null, FleetInputObject.FleetName ?? null, UpdateStrategyName, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,UpdateStrategyName=UpdateStrategyName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleetUpdateStrategy_UpdateViaIdentityFleetExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StrategyStage"))) + { + this.StrategyStage = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IUpdateStage[])(this.MyInvocation?.BoundParameters["StrategyStage"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleetUpdateStrategy + /// 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.ContainerServiceFleet.Models.IFleetUpdateStrategy + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleet_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleet_UpdateExpanded.cs new file mode 100644 index 00000000000..7015370f0b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleet_UpdateExpanded.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.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Fleet. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleet_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleet_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The Fleet resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the Fleet resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Fleet resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Fleet resource.", + SerializedName = @"fleetName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FleetName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags 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; } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleet_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleet_UpdateExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleet_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.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.FleetsGetWithResult(SubscriptionId, ResourceGroupName, Name, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.FleetsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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,IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleet_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..4a170cedd7b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/cmdlets/UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded.cs @@ -0,0 +1,644 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Cmdlets; + using System; + + /// update a Fleet. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzContainerServiceFleet_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Description(@"update a Fleet.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Generated] + public partial class UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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(); + + /// The Fleet resource. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IFleet _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.Fleet(); + + /// 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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.ContainerServiceFleetClient Client => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private string _ifMatch; + + /// The request should only proceed if an entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if an entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if an entity matches this string.", + SerializedName = @"If-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfMatch { get => this._ifMatch; set => this._ifMatch = value; } + + /// Backing field for property. + private string _ifNoneMatch; + + /// The request should only proceed if no entity matches this string. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The request should only proceed if no entity matches this string.")] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The request should only proceed if no entity matches this string.", + SerializedName = @"If-None-Match", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Header)] + public string IfNoneMatch { get => this._ifNoneMatch; set => this._ifNoneMatch = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.IContainerServiceFleetIdentity 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.ContainerServiceFleet.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags 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; } + + /// + /// 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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Cmdlets.UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzContainerServiceFleet_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; + clone.IfMatch = this.IfMatch; + clone.IfNoneMatch = this.IfNoneMatch; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FleetsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.FleetsGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.FleetsCreateOrUpdateViaIdentity(InputObject.Id, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.FleetName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FleetName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.FleetsGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.FleetsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FleetName ?? null, this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null, this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { IfMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfMatch") ? IfMatch : null,IfNoneMatch=this.InvocationInformation.BoundParameters.ContainsKey("IfNoneMatch") ? IfNoneMatch : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzContainerServiceFleet_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Models.ITrackedResourceTags)(this.MyInvocation?.BoundParameters["Tag"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Models.IFleet + /// 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.ContainerServiceFleet.Models.IFleet + var result = (await response); + WriteObject(result, false); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..4fa97ff2e30 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..2e0a73959f4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..dcf6d381c29 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is 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/Fleet.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..db3f1dd20e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet +{ + 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/Fleet.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..df3df1f5330 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet +{ + 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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..33da8b957d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..48e18066b45 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..a96c4a9fcbf --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..2a969e14852 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..7ddc1b8bb6a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..feebc934563 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..b1d82f627ff --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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: ContainerServiceFleet 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.ContainerServiceFleet.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.ContainerServiceFleet.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 ContainerServiceFleet".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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..d7034af5b0e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..7321a539b98 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..d2a069ac7e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..b67e0275873 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..90d24b670b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..6b5ac2a1fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..1e2ebca9fc5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..c3c6090608b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..58b1e189260 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,211 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.ContainerServiceFleet.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 static string CapitalizeFirstLetter(string text) + { + if (string.IsNullOrEmpty(text)) + return text; + + return char.ToUpper(text[0]) + text.Substring(1); + } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = CapitalizeFirstLetter(helpObject.GetProperty("Synopsis")); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + Description = CapitalizeFirstLetter(Description); + 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/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..c065d125f9f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..adf9efbb3ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,681 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.ContainerServiceFleet.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetLoginVerification() + { + if (!VariantGroup.IsInternal && IsAzure && !VariantGroup.IsModelCmdlet) + { + return $@" +{Indent}{Indent}$context = Get-AzContext +{Indent}{Indent}if (-not $context -and -not $testPlayback) {{ +{Indent}{Indent}{Indent}Write-Error ""No Azure login detected. Please run 'Connect-AzAccount' to log in."" +{Indent}{Indent}{Indent}exit +{Indent}{Indent}}} +"; + } + return ""; + } + + 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.ContainerServiceFleet.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 +{Indent}{Indent} +{Indent}{Indent}$testPlayback = $false +{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }} +{GetLoginVerification()}{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}if ($wrappedCmd -eq $null) {{ +{Indent}{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Function) +{Indent}{Indent}}} +{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}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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..c90cc2bc23a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,549 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft 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.ContainerServiceFleet.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 bool IsModelCmdlet { 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; + IsModelCmdlet = Variants.All(v => v.IsModelCmdlet); + 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 IsModelCmdlet { 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(); + IsModelCmdlet = 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(); + Description = PsHelpInfo.CapitalizeFirstLetter(Description); + // 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/Fleet.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..38f5ad14fa8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,136 @@ +/*--------------------------------------------------------------------------------------------- + * 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.ContainerServiceFleet +{ + [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 | AttributeTargets.Property)] + public class ModelCmdletAttribute : 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/Fleet.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..1a5c46c5f89 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..9c04446fd49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..b6670ab755f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..1db584af49e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..dbda73aa09b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..cdb699f5e4e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParameters, 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.ContainerServiceFleet.ContainerServiceFleetClient Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..c114a45e9a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..135f32bb010 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..36ba31e1504 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..bc53c444ffc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..a35e1d99f2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..9fd872c22e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..287a39e2d54 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..ef51c9cf693 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..519c70a7b25 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..da38e34dd65 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..139e1b263bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..a5c9bc73059 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..e1f8ad3baf4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..b6adf8bd3d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..ecf694aa44a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..70ca4aefab5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..0238da42c86 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..2ac81f6c4c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..92c8655e694 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..dc9a11641dc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..b140eda9db8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..263a13709c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..7b96a1454c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..e5a99703400 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..0797948a918 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..f491c95ce0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..d659a61ee6c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..0950c8bb692 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..5c6ab5c3595 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..0df665e864a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..149665f34ca --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..201af6f2f1d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..b23f7c39372 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..4d9dd685dd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..5f2da9d3bfd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..321576d0b3f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..d9d32ae625e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..4483c8774bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..cec58fd3693 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..2b773bd2531 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..dcf3086e494 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..5b2f0abab48 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..641a8baafb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..dd2677693b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..7c210201545 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..d97d500e978 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..94f53df40ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..fcd758d5086 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..99715eef682 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..8abcba344c3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..b3ac2d0f0d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..33d7b9e2c17 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..125c4a0984c --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..ed73f7ce8b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..1e91d4c16fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..870e662ee47 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..88039f4ce71 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..307c40c249b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,353 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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 description of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //Name of the module that is being deprecated + public string moduleName { get; set; } = String.IsNullOrEmpty(@"") ? @"Az.ContainerServiceFleet" : @""; + + //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.moduleName, 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/Fleet.Management.brown/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..53818507e71 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..492df705593 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..6a42c387813 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..071bcd5ca93 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..cca1eeb92fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..3c750af36ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..beb378c9886 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..9ddf6ed26d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..b16a6650cf6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..646f946287d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..9787577ff94 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..7f3eef0b5d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..e04729ad4bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..5bf10aa8232 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..9c60b38b696 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..01c88602ac4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..1b374c6a0d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..037b6bc3b8d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..8f28442eeff --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..c81d9062f60 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..ad527b24bc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..bfd9073f0cd --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..0eecd3e9aba --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..c49177b493d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..2192ffa9c4b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..f809a8ff3d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..2e979bfacb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..4ef90b70573 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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 in '{0}' from version : '{1}' + + + ```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/Fleet.Management.brown/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..0a874900708 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..dbd1614af8b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..d9fd22cf97e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..86079855f47 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..039c7c7b412 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..d5c63b5c718 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..d1b818fefae --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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.ContainerServiceFleet.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..0402a83e69b --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..30a26a892cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/how-to.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/how-to.md new file mode 100644 index 00000000000..17ded44c8ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.ContainerServiceFleet`. + +## Building `Az.ContainerServiceFleet` +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.ContainerServiceFleet` +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.ContainerServiceFleet` +To pack `Az.ContainerServiceFleet` 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.ContainerServiceFleet`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.ContainerServiceFleet.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.ContainerServiceFleet.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.ContainerServiceFleet`. + - `-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.ContainerServiceFleet` 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/Fleet.Management.brown/target/internal/Az.ContainerServiceFleet.internal.psm1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/internal/Az.ContainerServiceFleet.internal.psm1 new file mode 100644 index 00000000000..c94879684b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/internal/Az.ContainerServiceFleet.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.ContainerServiceFleet.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.ContainerServiceFleet.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/Fleet.Management.brown/target/internal/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/internal/README.md new file mode 100644 index 00000000000..b015aa5a604 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.ContainerServiceFleet`. Instead, this sub-module is imported by the `..\custom\Az.ContainerServiceFleet.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.ContainerServiceFleet.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.ContainerServiceFleet`. diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/license.txt b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/pack-module.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/resources/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/run-module.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/run-module.ps1 new file mode 100644 index 00000000000..abf7400c536 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/test-module.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/test-module.ps1 new file mode 100644 index 00000000000..994f78280d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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.ContainerServiceFleet.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/Fleet.Management.brown/target/test/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/README.md new file mode 100644 index 00000000000..d28996846ef --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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: + - https://github.com/Azure/azure-rest-api-specs/blob/d55f30f41f04e712de101fc9c17a591ca410bfed/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/Fleet.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/Fleet.Management.brown/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/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/Fleet.Management.brown/tspconfig.yaml b/tests-upgrade/tests-emitter/Fleet.Management.brown/tspconfig.yaml new file mode 100644 index 00000000000..13fef354427 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/tspconfig.yaml @@ -0,0 +1,79 @@ +parameters: + "service-dir": + default: "sdk/containerservicefleet" +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": + 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 + emitter-output-dir: "{project-root}/.." + arm-types-dir: "{project-root}/../../common-types/resource-management" + output-file: "{azure-resource-provider-folder}/{service-name}/fleet/{version-status}/{version}/fleets.json" + omit-unreachable-types: true + use-read-only-status-schema: true + "@azure-tools/typespec-python": + service-dir: "sdk/containerservice" + package-dir: "azure-mgmt-containerservicefleet" + namespace: "azure.mgmt.containerservicefleet" + generate-test: true + generate-sample: true + flavor: azure + "@azure-tools/typespec-java": + package-dir: "azure-resourcemanager-containerservicefleet" + namespace: "com.azure.resourcemanager.containerservicefleet" + service-name: "Container Service Fleet" + flavor: azure + "@azure-tools/typespec-go": + service-dir: "sdk/resourcemanager/containerservicefleet" + package-dir: "armcontainerservicefleet" + module: "github.com/Azure/azure-sdk-for-go/{service-dir}/{package-dir}" + fix-const-stuttering: true + flavor: "azure" + generate-samples: true + generate-fakes: true + head-as-boolean: true + inject-spans: true + "@azure-tools/typespec-ts": + service-dir: "sdk/containerservice" + flavor: azure + experimental-extensible-enums: true + package-dir: "arm-containerservicefleet" + package-details: + name: "@azure/arm-containerservicefleet" + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "ContainerServiceFleet/ContainerServiceFleet.Autorest" + clear-output-folder: true + emit-modeler-output: true + azure: true + module-version: 0.1.0 + prefix: 'Az' + subject-prefix: 'ContainerServiceFleet' + service-name: ContainerServiceFleet + module-name: "{prefix}.{service-name}" + 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: + variant: ^CreateViaIdentity.*$ + remove: true diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/update/autoupgradeprofile.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/autoupgradeprofile.tsp new file mode 100644 index 00000000000..bac1ad2946a --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/autoupgradeprofile.tsp @@ -0,0 +1,214 @@ +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./../helpers.tsp"; +import "./run.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.ResourceManager; +using Azure.ResourceManager.Foundations; +using Azure.Core; +using Azure.Core.Traits; +using TypeSpec.OpenAPI; + +namespace Microsoft.ContainerService; + +@resource("autoUpgradeProfiles") +@parentResource(Fleet) +@added(Versions.v2024_05_02_preview) +@doc("The AutoUpgradeProfile resource.") +model AutoUpgradeProfile + is Azure.ResourceManager.ProxyResource { + @doc("The name of the AutoUpgradeProfile resource.") + @key("autoUpgradeProfileName") + @segment("autoUpgradeProfiles") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + @path + @visibility(Lifecycle.Create, Lifecycle.Read) + name: string; + + ...EntityTagProperty; +} + +@doc("The provisioning state of the AutoUpgradeProfile resource.") +union AutoUpgradeProfileProvisioningState { + string, + ResourceProvisioningState, +} + +@doc("The properties of the AutoUpgradeProfile.") +@added(Versions.v2024_05_02_preview) +model AutoUpgradeProfileProperties { + @visibility(Lifecycle.Read) + @doc("The provisioning state of the AutoUpgradeProfile resource.") + provisioningState?: AutoUpgradeProfileProvisioningState; + + @visibility(Lifecycle.Create, Lifecycle.Read) + @doc("The resource id of the UpdateStrategy resource to reference. If not specified, the auto upgrade will run on all clusters which are members of the fleet.") + updateStrategyId?: FleetUpdateStrategyResourceId; + + @doc("Configures how auto-upgrade will be run.") + channel: UpgradeChannel; + + @doc("The node image upgrade to be applied to the target clusters in auto upgrade.") + nodeImageSelection?: AutoUpgradeNodeImageSelection; + + @doc(""" + If set to False: the auto upgrade has effect - target managed clusters will be upgraded on schedule. + If set to True: the auto upgrade has no effect - no upgrade will be run on the target managed clusters. + This is a boolean and not an enum because enabled/disabled are all available states of the auto upgrade profile. + By default, this is set to False. + """) + disabled?: boolean; + + @doc("The status of the auto upgrade profile.") + @added(Versions.v2025_03_01) + autoUpgradeProfileStatus?: AutoUpgradeProfileStatus; + + @doc(""" + This is the target Kubernetes version for auto-upgrade. The format must be `{major version}.{minor version}`. For example, "1.30". + By default, this is empty. + If upgrade channel is set to TargetKubernetesVersion, this field must not be empty. + If upgrade channel is Rapid, Stable or NodeImage, this field must be empty. + """) + @added(Versions.v2025_04_01_preview) + targetKubernetesVersion?: string; + + @doc(""" + If upgrade channel is not TargetKubernetesVersion, this field must be False. + If set to True: Fleet auto upgrade will continue generate update runs for patches of minor versions earlier than N-2 + (where N is the latest supported minor version) if those minor versions support Long-Term Support (LTS). + By default, this is set to False. + For more information on AKS LTS, please see https://learn.microsoft.com/en-us/azure/aks/long-term-support + """) + @added(Versions.v2025_04_01_preview) + longTermSupport?: boolean; +} + +@doc("Configuration of how auto upgrade will be run.") +union UpgradeChannel { + string, + + @doc(""" + Upgrades the clusters kubernetes version to the latest supported patch release on minor version N-1, where N is the latest supported minor version. + For example, if a cluster runs version 1.17.7 and versions 1.17.9, 1.18.4, 1.18.6, and 1.19.1 are available, the cluster upgrades to 1.18.6. + """) + Stable: "Stable", + + @doc("Upgrades the clusters kubernetes version to the latest supported patch release on the latest supported minor version.") + Rapid: "Rapid", + + @doc("Upgrade node image version of the clusters.") + NodeImage: "NodeImage", + + @doc(""" + Upgrades the clusters Kubernetes version to the latest supported patch version of the specified target Kubernetes version. + For information on the behavior of update run for Kubernetes version upgrade, + see https://learn.microsoft.com/en-us/azure/kubernetes-fleet/update-orchestration?tabs=azure-portal + """) + @added(Versions.v2025_04_01_preview) + TargetKubernetesVersion: "TargetKubernetesVersion", +} + +@doc("The node image upgrade to be applied to the target clusters in auto upgrade.") +@added(Versions.v2024_05_02_preview) +model AutoUpgradeNodeImageSelection { + @visibility(Lifecycle.Create, Lifecycle.Read) + @doc("The node image upgrade type.") + type: AutoUpgradeNodeImageSelectionType; +} + +@doc("The node image upgrade type.") +@added(Versions.v2024_05_02_preview) +union AutoUpgradeNodeImageSelectionType { + string, + + @doc("Use the latest image version when upgrading nodes. Clusters may use different image versions (e.g., 'AKSUbuntu-1804gen2containerd-2021.10.12' and 'AKSUbuntu-1804gen2containerd-2021.10.19') because, for example, the latest available version is different in different regions.") + Latest: "Latest", + + @doc("The image versions to upgrade nodes to are selected as described below: for each node pool in managed clusters affected by the update run, the system selects the latest image version such that it is available across all other node pools (in all other clusters) of the same image type. As a result, all node pools of the same image type will be upgraded to the same image version. For example, if the latest image version for image type 'AKSUbuntu-1804gen2containerd' is 'AKSUbuntu-1804gen2containerd-2021.10.12' for a node pool in cluster A in region X, and is 'AKSUbuntu-1804gen2containerd-2021.10.17' for a node pool in cluster B in region Y, the system will upgrade both node pools to image version 'AKSUbuntu-1804gen2containerd-2021.10.12'.") + Consistent: "Consistent", +} + +@added(Versions.v2024_05_02_preview) +@armResourceOperations +interface AutoUpgradeProfiles { + get is ArmResourceRead; + + createOrUpdate is ArmResourceCreateOrUpdateAsync< + AutoUpgradeProfile, + BaseParameters & + IfMatchParameters & + IfNoneMatchParameters + >; + + delete is ArmResourceDeleteWithoutOkAsync< + AutoUpgradeProfile, + BaseParameters & IfMatchParameters + >; + + listByFleet is ArmResourceListByParent; +} + +@doc("AutoUpgradeProfileStatus is the status of an auto upgrade profile.") +@added(Versions.v2025_03_01) +model AutoUpgradeProfileStatus { + @doc("The UTC time of the last attempt to automatically create and start an UpdateRun as triggered by the release of new versions.") + @visibility(Lifecycle.Read) + lastTriggeredAt?: utcDateTime; + + @doc("The status of the last AutoUpgrade trigger.") + @visibility(Lifecycle.Read) + lastTriggerStatus?: AutoUpgradeLastTriggerStatus; + + @doc("The error details of the last trigger.") + @visibility(Lifecycle.Read) + lastTriggerError?: Azure.ResourceManager.Foundations.ErrorDetail; // https://github.com/Azure/azure-rest-api-specs/blob/1de0b5315d62e1b40052bad2c9a2f2c89d84ff0f/specification/common-types/resource-management/v5/types.json#L260 + + @doc("The target Kubernetes version or node image versions of the last trigger.") + @visibility(Lifecycle.Read) + lastTriggerUpgradeVersions?: string[]; +} + +@doc("AutoUpgradeLastTriggerStatus is the status of the last AutoUpgrade trigger (attempt to automatically create and start UpdateRun when there are new released versions) of an auto upgrade profile.") +@added(Versions.v2025_03_01) +union AutoUpgradeLastTriggerStatus { + string, + + @doc("The last AutoUpgrade trigger was succeeded.") + Succeeded: "Succeeded", + + @doc("The last AutoUpgrade trigger failed.") + Failed: "Failed", +} + +@added(Versions.v2025_03_01) +@armResourceOperations +interface AutoUpgradeProfileOperations { + #suppress "@azure-tools/typespec-azure-resource-manager/lro-location-header" "use azure-async instead" + @useFinalStateVia("azure-async-operation") + @doc("Generates an update run for a given auto upgrade profile.") + generateUpdateRun is Azure.ResourceManager.ArmResourceActionAsync< + AutoUpgradeProfile, + void, + GenerateResponse, + BaseParameters, + LroHeaders = ArmAsyncOperationHeader & + ArmLroLocationHeader & + IfMatchParameters + >; +} + +@added(Versions.v2025_03_01) +@doc("GenerateResponse is the response of a generate request.") +model GenerateResponse { + @visibility(Lifecycle.Read) + @doc("The ARM resource id of the generated UpdateRun. e.g.: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/fleets/{fleetName}/updateRuns/{updateRunName}'.") + id: string; +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/update/common.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/common.tsp new file mode 100644 index 00000000000..938677ff119 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/common.tsp @@ -0,0 +1,81 @@ +import "@typespec/openapi"; + +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace Microsoft.ContainerService; + +@doc(""" + Defines the update sequence of the clusters via stages and groups. + + Stages within a run are executed sequentially one after another. + Groups within a stage are executed in parallel. + Member clusters within a group are updated sequentially one after another. + + A valid strategy contains no duplicate groups within or across stages. + """) +model UpdateRunStrategy { + @Azure.ResourceManager.identifiers(#["name"]) + @doc("The list of stages that compose this update run. Min size: 1.") + stages: UpdateStage[]; +} + +@doc("Defines a stage which contains the groups to update and the steps to take (e.g., wait for a time period) before starting the next stage.") +model UpdateStage { + @doc("The name of the stage. Must be unique within the UpdateRun.") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + name: string; + + @Azure.ResourceManager.identifiers(#["name"]) + @doc("Defines the groups to be executed in parallel in this stage. Duplicate groups are not allowed. Min size: 1.") + groups?: UpdateGroup[]; + + @doc("The time in seconds to wait at the end of this stage before starting the next one. Defaults to 0 seconds if unspecified.") + afterStageWaitInSeconds?: int32; + + @doc("A list of Gates that will be created before this Stage is executed.") + @added(Versions.v2025_04_01_preview) + @extension("x-ms-identifiers", #[]) + beforeGates?: GateConfiguration[]; + + @doc("A list of Gates that will be created after this Stage is executed.") + @added(Versions.v2025_04_01_preview) + @extension("x-ms-identifiers", #[]) + afterGates?: GateConfiguration[]; +} + +@doc("A group to be updated.") +model UpdateGroup { + @doc(""" + Name of the group. + It must match a group name of an existing fleet member. + """) + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + name: string; + + @doc("A list of Gates that will be created before this Group is executed.") + @added(Versions.v2025_04_01_preview) + @extension("x-ms-identifiers", #[]) + beforeGates?: GateConfiguration[]; + + @doc("A list of Gates that will be created after this Group is executed.") + @added(Versions.v2025_04_01_preview) + @extension("x-ms-identifiers", #[]) + afterGates?: GateConfiguration[]; +} + +@doc("GateConfiguration is used to define where Gates should be placed within the Update Run.") +@added(Versions.v2025_04_01_preview) +model GateConfiguration { + @doc("The human-readable display name of the Gate.") + @minLength(1) + @maxLength(100) + displayName?: string; + + @doc("The type of the Gate determines how it is completed.") + type: GateType; +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/update/run.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/run.tsp new file mode 100644 index 00000000000..4494ac84d48 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/run.tsp @@ -0,0 +1,460 @@ +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./../helpers.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.ResourceManager; +using TypeSpec.OpenAPI; + +namespace Microsoft.ContainerService; + +@resource("updateRuns") +@parentResource(Fleet) +@doc("A multi-stage process to perform update operations across members of a Fleet.") +model UpdateRun is ProxyResource { + @doc("The name of the UpdateRun resource.") + @key("updateRunName") + @segment("updateRuns") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + @path + @visibility(Lifecycle.Create, Lifecycle.Read) + name: string; + + ...EntityTagProperty; +} + +@doc("The provisioning state of the UpdateRun resource.") +union UpdateRunProvisioningState { + string, + ResourceProvisioningState, +} + +scalar FleetUpdateStrategyResourceId + extends Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.ContainerService/fleets/updateStrategies", + } + ]>; + +scalar AutoUpgradeProfileId + extends Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.ContainerService/fleets/updateRuns", + } + ]>; + +scalar GateResourceId + extends Azure.Core.armResourceIdentifier<[ + { + type: "Microsoft.ContainerService/fleets/gates", + } + ]>; + +@doc("The properties of the UpdateRun.") +model UpdateRunProperties { + @visibility(Lifecycle.Read) + @doc("The provisioning state of the UpdateRun resource.") + provisioningState?: UpdateRunProvisioningState; + + @doc(""" + The resource id of the FleetUpdateStrategy resource to reference. + + When creating a new run, there are three ways to define a strategy for the run: + 1. Define a new strategy in place: Set the "strategy" field. + 2. Use an existing strategy: Set the "updateStrategyId" field. (since 2023-08-15-preview) + 3. Use the default strategy to update all the members one by one: Leave both "updateStrategyId" and "strategy" unset. (since 2023-08-15-preview) + + Setting both "updateStrategyId" and "strategy" is invalid. + + UpdateRuns created by "updateStrategyId" snapshot the referenced UpdateStrategy at the time of creation and store it in the "strategy" field. + Subsequent changes to the referenced FleetUpdateStrategy resource do not propagate. + UpdateRunStrategy changes can be made directly on the "strategy" field before launching the UpdateRun. + """) + @added(Versions.v2023_08_15_preview) + updateStrategyId?: FleetUpdateStrategyResourceId; + + @doc(""" + The strategy defines the order in which the clusters will be updated. + If not set, all members will be updated sequentially. The UpdateRun status will show a single UpdateStage and a single UpdateGroup targeting all members. + The strategy of the UpdateRun can be modified until the run is started. + """) + strategy?: UpdateRunStrategy; + + @doc("The update to be applied to all clusters in the UpdateRun. The managedClusterUpdate can be modified until the run is started.") + managedClusterUpdate: ManagedClusterUpdate; + + @visibility(Lifecycle.Read) + @doc("The status of the UpdateRun.") + status?: UpdateRunStatus; + + @visibility(Lifecycle.Read) + @doc("AutoUpgradeProfileId is the id of an auto upgrade profile resource.") + @added(Versions.v2025_03_01) + autoUpgradeProfileId?: AutoUpgradeProfileId; +} + +@doc("The update to be applied to the ManagedClusters.") +model ManagedClusterUpdate { + @doc("The upgrade to apply to the ManagedClusters.") + upgrade: ManagedClusterUpgradeSpec; + + @visibility(Lifecycle.Create, Lifecycle.Read) + @doc("The node image upgrade to be applied to the target nodes in update run.") + @added(Versions.v2023_06_15_preview) + nodeImageSelection?: NodeImageSelection; +} + +@doc("The node image upgrade to be applied to the target nodes in update run.") +@added(Versions.v2023_06_15_preview) +model NodeImageSelection { + @visibility(Lifecycle.Create, Lifecycle.Read) + @doc("The node image upgrade type.") + type: NodeImageSelectionType; + + @added(Versions.v2024_05_02_preview) + @doc("Custom node image versions to upgrade the nodes to. This field is required if node image selection type is Custom. Otherwise, it must be empty. For each node image family (e.g., 'AKSUbuntu-1804gen2containerd'), this field can contain at most one version (e.g., only one of 'AKSUbuntu-1804gen2containerd-2023.01.12' or 'AKSUbuntu-1804gen2containerd-2023.02.12', not both). If the nodes belong to a family without a matching image version in this field, they are not upgraded.") + @identifiers(#["version"]) + customNodeImageVersions?: NodeImageVersion[]; +} + +@doc("The node image upgrade type.") +@added(Versions.v2023_06_15_preview) +union NodeImageSelectionType { + string, + + @doc("Use the latest image version when upgrading nodes. Clusters may use different image versions (e.g., 'AKSUbuntu-1804gen2containerd-2021.10.12' and 'AKSUbuntu-1804gen2containerd-2021.10.19') because, for example, the latest available version is different in different regions.") + "Latest", + + @doc("The image versions to upgrade nodes to are selected as described below: for each node pool in managed clusters affected by the update run, the system selects the latest image version such that it is available across all other node pools (in all other clusters) of the same image type. As a result, all node pools of the same image type will be upgraded to the same image version. For example, if the latest image version for image type 'AKSUbuntu-1804gen2containerd' is 'AKSUbuntu-1804gen2containerd-2021.10.12' for a node pool in cluster A in region X, and is 'AKSUbuntu-1804gen2containerd-2021.10.17' for a node pool in cluster B in region Y, the system will upgrade both node pools to image version 'AKSUbuntu-1804gen2containerd-2021.10.12'.") + "Consistent", + + @added(Versions.v2024_05_02_preview) + @doc("Upgrade the nodes to the custom image versions. When set, update run will use node image versions provided in customNodeImageVersions to upgrade the nodes. If set, customNodeImageVersions must not be empty.") + "Custom", +} + +scalar KubernetesVersion extends string; + +@doc("The upgrade to apply to a ManagedCluster.") +model ManagedClusterUpgradeSpec { + @doc("ManagedClusterUpgradeType is the type of upgrade to be applied.") + type: ManagedClusterUpgradeType; + + @doc("The Kubernetes version to upgrade the member clusters to.") + kubernetesVersion?: KubernetesVersion; +} + +@doc("The type of upgrade to perform when targeting ManagedClusters.") +union ManagedClusterUpgradeType { + string, + + @doc("Full upgrades the control plane and all agent pools of the target ManagedClusters. Requires the ManagedClusterUpgradeSpec.KubernetesVersion property to be set.") + "Full", + + @doc("NodeImageOnly upgrades only the node images of the target ManagedClusters. Requires the ManagedClusterUpgradeSpec.KubernetesVersion property to NOT be set.") + "NodeImageOnly", + + @doc("ControlPlaneOnly upgrades only targets the KubernetesVersion of the ManagedClusters and will not be applied to the AgentPool. Requires the ManagedClusterUpgradeSpec.KubernetesVersion property to be set.") + @added(Versions.v2024_02_02_preview) + "ControlPlaneOnly", +} + +@doc("The state of the UpdateRun, UpdateStage, UpdateGroup, or MemberUpdate.") +union UpdateState { + string, + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that has not been started.") + "NotStarted", + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that is running.") + "Running", + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that is being stopped.") + "Stopping", + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that has stopped.") + "Stopped", + + @added(Versions.v2023_06_15_preview) + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that has been skipped.") + "Skipped", + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that has failed.") + "Failed", + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that is pending.") + "Pending", + + @doc("The state of an UpdateRun/UpdateStage/UpdateGroup/MemberUpdate that has completed.") + "Completed", +} + +@doc("The status for an operation or group of operations.") +model UpdateStatus { + @visibility(Lifecycle.Read) + @doc("The time the operation or group was started.") + startTime?: utcDateTime; + + @visibility(Lifecycle.Read) + @doc("The time the operation or group was completed.") + completedTime?: utcDateTime; + + @visibility(Lifecycle.Read) + @doc("The State of the operation or group.") + state?: UpdateState; + + @visibility(Lifecycle.Read) + @doc("The error details when a failure is encountered.") + error?: Azure.ResourceManager.Foundations.ErrorDetail; // https://github.com/Azure/azure-rest-api-specs/blob/1de0b5315d62e1b40052bad2c9a2f2c89d84ff0f/specification/common-types/resource-management/v5/types.json#L260 +} + +@doc("The status of a UpdateRun.") +model UpdateRunStatus { + @visibility(Lifecycle.Read) + @doc("The status of the UpdateRun.") + status?: UpdateStatus; + + @visibility(Lifecycle.Read) + @identifiers(#["name"]) + @doc("The stages composing an update run. Stages are run sequentially withing an UpdateRun.") + stages?: UpdateStageStatus[]; + + @visibility(Lifecycle.Read) + @doc("The node image upgrade specs for the update run. It is only set in update run when `NodeImageSelection.type` is `Consistent`.") + @added(Versions.v2023_06_15_preview) + nodeImageSelection?: NodeImageSelectionStatus; +} + +@doc("The node image upgrade specs for the update run.") +@added(Versions.v2023_06_15_preview) +model NodeImageSelectionStatus { + @visibility(Lifecycle.Read) + @identifiers(#["version"]) + @doc("The image versions to upgrade the nodes to.") + selectedNodeImageVersions?: NodeImageVersion[]; +} + +@doc("The node upgrade image version.") +@added(Versions.v2023_06_15_preview) +model NodeImageVersion { + @visibility(Lifecycle.Read) + @doc("The image version to upgrade the nodes to (e.g., 'AKSUbuntu-1804gen2containerd-2022.12.13').") + version?: string; +} + +@doc("The status of a UpdateStage.") +model UpdateStageStatus { + @visibility(Lifecycle.Read) + @doc("The status of the UpdateStage.") + status?: UpdateStatus; + + @visibility(Lifecycle.Read) + @doc("The name of the UpdateStage.") + name?: string; + + @visibility(Lifecycle.Read) + @identifiers(#["name"]) + @doc("The list of groups to be updated as part of this UpdateStage.") + groups?: UpdateGroupStatus[]; + + @visibility(Lifecycle.Read) + @extension("x-ms-identifiers", #[]) + @doc("The list of Gates that will run before this UpdateStage.") + @added(Versions.v2025_04_01_preview) + beforeGates?: UpdateRunGateStatus[]; + + @visibility(Lifecycle.Read) + @extension("x-ms-identifiers", #[]) + @doc("The list of Gates that will run after this UpdateStage.") + @added(Versions.v2025_04_01_preview) + afterGates?: UpdateRunGateStatus[]; + + @visibility(Lifecycle.Read) + @doc("The status of the wait period configured on the UpdateStage.") + afterStageWaitStatus?: WaitStatus; +} + +@doc("The status of a UpdateGroup.") +model UpdateGroupStatus { + @visibility(Lifecycle.Read) + @doc("The status of the UpdateGroup.") + status?: UpdateStatus; + + @visibility(Lifecycle.Read) + @doc("The name of the UpdateGroup.") + name?: string; + + @visibility(Lifecycle.Read) + @identifiers(#["name"]) + @doc("The list of member this UpdateGroup updates.") + members?: MemberUpdateStatus[]; + + @visibility(Lifecycle.Read) + @extension("x-ms-identifiers", #[]) + @doc("The list of Gates that will run before this UpdateGroup.") + @added(Versions.v2025_04_01_preview) + beforeGates?: UpdateRunGateStatus[]; + + @visibility(Lifecycle.Read) + @extension("x-ms-identifiers", #[]) + @doc("The list of Gates that will run after this UpdateGroup.") + @added(Versions.v2025_04_01_preview) + afterGates?: UpdateRunGateStatus[]; +} + +@doc("The status of the wait duration.") +model WaitStatus { + @visibility(Lifecycle.Read) + @doc("The status of the wait duration.") + status?: UpdateStatus; + + @visibility(Lifecycle.Read) + @doc("The wait duration configured in seconds.") + waitDurationInSeconds?: int32; +} + +@doc("The status of the Gate, as represented in the Update Run.") +@added(Versions.v2025_04_01_preview) +model UpdateRunGateStatus { + @doc("The human-readable display name of the Gate.") + @visibility(Lifecycle.Read) + @minLength(1) + @maxLength(100) + displayName?: string; + + @doc("The resource id of the Gate.") + @visibility(Lifecycle.Read) + gateId?: GateResourceId; + + @doc("The status of the Gate.") + @visibility(Lifecycle.Read) + status?: UpdateStatus; +} + +@doc("The status of a member update operation.") +model MemberUpdateStatus { + @visibility(Lifecycle.Read) + @doc("The status of the MemberUpdate operation.") + status?: UpdateStatus; + + @visibility(Lifecycle.Read) + @doc("The name of the FleetMember.") + name?: string; + + @visibility(Lifecycle.Read) + @doc("The Azure resource id of the target Kubernetes cluster.") + clusterResourceId?: string; + + @visibility(Lifecycle.Read) + @doc("The operation resource id of the latest attempt to perform the operation.") + operationId?: string; + + @visibility(Lifecycle.Read) + @doc("The status message after processing the member update operation.") + @added(Versions.v2023_06_15_preview) + message?: string; +} + +@doc("The target type of a skip request.") +@added(Versions.v2024_02_02_preview) +union TargetType { + string, + + @doc("Skip the update of a member.") + Member: "Member", + + @doc("Skip the update of a group.") + Group: "Group", + + @doc("Skip the update of an entire stage including the after stage wait.") + Stage: "Stage", + + @doc("Skip the update of the after stage wait of a certain stage.") + AfterStageWait: "AfterStageWait", +} + +@doc("The definition of a single skip request.") +@added(Versions.v2024_02_02_preview) +model SkipTarget { + @doc("The skip target type.") + type: TargetType; + + @doc(""" + The skip target's name. + To skip a member/group/stage, use the member/group/stage's name; + Tp skip an after stage wait, use the parent stage's name. + """) + name: string; +} + +@doc("The properties of a skip operation containing multiple skip requests.") +@added(Versions.v2024_02_02_preview) +model SkipProperties { + @doc("The targets to skip.") + @identifiers(#["type", "name"]) + targets: SkipTarget[]; +} + +@added(Versions.v2023_03_15_preview) +@armResourceOperations +interface UpdateRuns { + get is ArmResourceRead; + + #suppress "@azure-tools/typespec-azure-core/invalid-final-state" "MUST CHANGE AT NEXT VERSION" + @Azure.Core.useFinalStateVia("azure-async-operation") + createOrUpdate is ArmResourceCreateOrUpdateAsync< + UpdateRun, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters & + IfNoneMatchParameters, + LroHeaders = Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "deprecated" "Existing API" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-delete-operation-response-codes" "Existing API" + delete is ArmResourceDeleteAsync< + UpdateRun, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + /** List UpdateRun resources by Fleet */ + listByFleet is ArmResourceListByParent; + + #suppress "@azure-tools/typespec-azure-resource-manager/arm-post-operation-response-codes" "Existing API" + @doc("Starts an UpdateRun.") + start is ArmResourceActionAsync< + UpdateRun, + void, + UpdateRun, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + #suppress "@azure-tools/typespec-azure-resource-manager/arm-post-operation-response-codes" "Existing API" + @doc("Stops an UpdateRun.") + stop is ArmResourceActionAsync< + UpdateRun, + void, + UpdateRun, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; + + @doc("Skips one or a combination of member/group/stage/afterStageWait(s) of an update run.") + @added(Versions.v2024_02_02_preview) + skip is ArmResourceActionAsync< + UpdateRun, + SkipProperties, + UpdateRun, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters + >; +} diff --git a/tests-upgrade/tests-emitter/Fleet.Management.brown/update/strategy.tsp b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/strategy.tsp new file mode 100644 index 00000000000..779fb7b0b29 --- /dev/null +++ b/tests-upgrade/tests-emitter/Fleet.Management.brown/update/strategy.tsp @@ -0,0 +1,85 @@ +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "./../helpers.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.ResourceManager; +using Azure.Core; +using Azure.Core.Traits; +using TypeSpec.OpenAPI; + +namespace Microsoft.ContainerService; + +@resource("updateStrategies") +@parentResource(Fleet) +@added(Versions.v2023_08_15_preview) +@doc("Defines a multi-stage process to perform update operations across members of a Fleet.") +model FleetUpdateStrategy is ProxyResource { + @doc("The name of the UpdateStrategy resource.") + @key("updateStrategyName") + @segment("updateStrategies") + @pattern("^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") + @minLength(1) + @maxLength(50) + @path + @visibility(Lifecycle.Create, Lifecycle.Read) + name: string; + + ...EntityTagProperty; +} + +@doc("The provisioning state of the UpdateStrategy resource.") +union FleetUpdateStrategyProvisioningState { + string, + ResourceProvisioningState, +} + +@doc("The properties of the UpdateStrategy.") +model FleetUpdateStrategyProperties { + @visibility(Lifecycle.Read) + @doc("The provisioning state of the UpdateStrategy resource.") + provisioningState?: FleetUpdateStrategyProvisioningState; + + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @doc("Defines the update sequence of the clusters.") + strategy: UpdateRunStrategy; +} + +@added(Versions.v2023_08_15_preview) +@armResourceOperations +interface FleetUpdateStrategies { + get is ArmResourceRead; + + #suppress "@azure-tools/typespec-azure-core/invalid-final-state" "MUST CHANGE AT NEXT API VERSION UPDATE" + @Azure.Core.useFinalStateVia("azure-async-operation") + createOrUpdate is ArmResourceCreateOrUpdateAsync< + FleetUpdateStrategy, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters & + IfNoneMatchParameters, + LroHeaders = Azure.Core.Foundations.RetryAfterHeader + >; + + #suppress "deprecated" "Existing API" + #suppress "@azure-tools/typespec-azure-resource-manager/arm-delete-operation-response-codes" "Existing API" + #suppress "@azure-tools/typespec-azure-core/no-openapi" "DO NOT COPY - migrate to LRO apis" + @useFinalStateVia("azure-async-operation") + // @extension( + // "x-ms-long-running-operation-options", + // #{ `final-state-via`: "azure-async-operation" } + // ) + delete is ArmResourceDeleteAsync< + FleetUpdateStrategy, + Azure.ResourceManager.Foundations.BaseParameters & + IfMatchParameters, + LroHeaders = ArmAsyncOperationHeader & Azure.Core.Foundations.RetryAfterHeader + >; + + /** List FleetUpdateStrategy resources by Fleet */ + listByFleet is ArmResourceListByParent; +} diff --git a/tests-upgrade/tests-emitter/configuration.json b/tests-upgrade/tests-emitter/configuration.json index 9443e7f8eaa..882a4ef3cc8 100644 --- a/tests-upgrade/tests-emitter/configuration.json +++ b/tests-upgrade/tests-emitter/configuration.json @@ -24,6 +24,10 @@ "Sphere.Management", "StandbyPool.Management", "Workloads.SAPVirtualInstance.Management", + "Chaos.Management.brown", + "Dashboard.Management.brown", + "DataReplication.Management.brown", + "Fleet.Management.brown", "HardwareSecurityModules.Management.brown", "HybridKubernetes.Management.brown", "Microsoft.AVS.Management.brown", @@ -55,6 +59,10 @@ "Sphere.Management", "StandbyPool.Management", "Workloads.SAPVirtualInstance.Management", + "Chaos.Management.brown", + "Dashboard.Management.brown", + "DataReplication.Management.brown", + "Fleet.Management.brown", "HardwareSecurityModules.Management.brown", "HybridKubernetes.Management.brown", "Microsoft.AVS.Management.brown",